# Write Higher Order Arrow Functions map and filter

Tell us what’s happening:
I super don’t understand filter() or map(). I have looked at code samples and MDN and W3 Schools and I still don’t understand how to use it. I just now have a basic understanding of WHY you would use it.

``````
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
"use strict";
// change code below this line
const squaredIntegers = arr;
// change code above this line
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36`.

• filter

loops over an array, and return a new array containing only the value that were true for the provided function callback.

This means that the following two examples are equivalent:

``````const a = [1, 10, 3, 20, 15, 4];

// use built in filter
const withFilter = a.filter(val => val >= 10);

// we create it imperatively
const manualFilter = arr => {
// new array
let newArr = [];
// loop over
for(let i = 0; i < arr.length; i++) {
// keep only value that are true
if(arr[i] >= 10) {
newArr.push(arr[i])
}
}
// return new array
return newArr
}
const manual = manualFilter(a);

console.log(a); // [ 1, 10, 3, 20, 15, 4 ]
console.log(withFilter); // [ 10, 20, 15 ]
console.log(manual); // [ 10, 20, 15 ]
``````

As you can see they both produce the same output, since both loop, return a new array with only the true values

• map
Likewise filter, map loop over an array and return a new array, but with the values “updated” to what is returned from the provided function.
``````const a = [1, 10, 20];

// use built in filter
const withMap = a.map(val => val + 10);

// we create it imperatively
const manualMap = arr => {
// new array
let newArr = [];
// loop over
for(let i = 0; i < arr.length; i++) {
// add the new updated value
newArr.push(arr[i] + 10);
}
// return new array
return newArr
}
const manual = manualMap(a);

console.log(a); // [ 1, 10, 20 ]
console.log(withMap); // [ 11, 20, 30 ]
console.log(manual); // [ 11, 20, 30 ]
``````
• arrow function

Lastly, remember that arrow functions are an alternative syntax to regular functions, with the return statement implicit.
So the two are equivalent

``````array.map(function(val) {
return val + 10
})

array.map( (val) => val + 10)
``````

[phew] that was long,
I hope it will help in your attempt to map and / or filter the array

2 Likes

map lets you apply a function to each item in the array.
filter returns an item only if a function returns true
both only take functions as arguments
both methods return a new array
think of it as a for loop but easier to write

1 Like

I understand it now!!! Thank you so much!!!