Javascript map and filter functions

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here is an example of a Javascript map function in action. It is a method of the array class, so we first have to create an array myList…

let myList = [2, 4, 3, 7, 8];
let doublesList = myList.map(x => x * 2);
console.log(doublesList);
// [4, 8, 6, 14, 16]

We call the map method on the array passing it an inline anonymous arrow function. The map function does not alter its own list, but returns a new list with the function applied to each element of the original list.

In our case, our map function doubles the value of each element.

The filter method takes a function that returns truthy or falsy. If falsy, it will filter out that member from the array.

let myList = [2, 4, 3, 7, 8];
let evensList = myList.filter(x => x % 2 == 0);
console.log(evensList);
// [2, 4, 8]

It too does not alter the original array, but returns a new array. In our case, the new array only contains evens, because we filtered out the odds.


Related Posts

Tags

Share This