Javascript Map/Filter
Overview
map, reduce, and filter are all array helper methods of JavaScript.
Each one will iterate over an array and perform a transformation or computation.
Each will return a new array based on the result of the function.
In this article, you will learn why and how to use each one.
In one Picture
Array.map()
Syntax
let new_array = arr.map(function callback( element, index, array) {
// return element for new_array
}[, thisArg])
In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.
Let's see some real life example of where it can be useful.
Double each number of an array
const numbers = [1, 4, 9, 16];
// pass a function to map
const doubled = input.map(x => x * 2);
console.log(doubled);
// expected output: Array [2, 8, 18, 32]
console.log(numbers);
// expected output: [1, 4, 9, 16]
Notable Points:
- input array is unchanged
- map operation produced a new array as result
Reformatting Array Objects
When we want to handle the modification of an array of object, Yes ☺ .map()
can be our answer for that.
.map()
can be used to iterate through objects in an array and we can modify that object according to our
need and return a new array. This modification is done based on what is returned in the callback function. Here's an example:
const owls = [
{ name: 'Great horned owl', likes: 'meat' },
{ name: 'Barn Owl', likes: 'fish' },
{ name: 'Snowy Owl', likes: 'fruits' },
{ name: 'Barred Owl',likes:'mice'}
]
const newOwls = owls.map(owl => {
const container = {};
container.name = owl.name;
container.likes= owl.likes;
container.age = owl.name.length;
return container;
})
newOlws
array :
[
{ name: 'Great horned owl', likes: 'meat', age: 16 },
{ name: 'Barn Owl', likes: 'fish', age: 8 },
{ name: 'Snowy Owl', likes: 'fruits', age: 9 },
{ name: 'Barred Owl', likes: 'mice', age: 10 }
]
In our above example we have an array of owl object and our each owl object has name
& likes
properties.
We want to add one additional property age
for each owl object base on their length of the name
property
and map() handles that elegantly.
Rendering List in React (JSX)
.map()
has an extensive use in ReactJS
.
JavaScript libraries like React utilize .map() to render items in a list. This requires JSX syntax however as .map() method is wrapped in mustache-like JSX syntax. Here's a good example of a React component.
import React from "react";
import ReactDOM from "react-dom";
const owls = ["Great horned owl", "Barn Owl", "Snowy Owl", "Barred Owl"];
const NamesList = () => (
<div>
<ul>{owls.map(name => <li key={name}> {name} </li>)}</ul>
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<NamesList />, rootElement);
All we did is simply modify each object in the array using the bracket and dot notation. This use case can be employed to process or condense received data before being saved or parsed on a frontend application.
Array.filter()
The Array.filter()
method creates a new array with only elements, that pass a test we include as a callback function.
filter()
does not mutate the array on which it is called. Let's see some examples:
Filtering out all odd value
function isEven(value) {
return value % 2 ===0
}
const evenList = [1,2,3,4,5,6,7,8,9,10,11,12].filter(isEven)
// evenList is [2,4,6,8,10,12]
Above example uses filter()
to create a filtered array that has only even numbers.
Filter Array Items based On Search Criteria (query)
Let's filter owls based on search query
const owls = ["Great horned owl", "Barn Owl", "Snowy Owl", "Barred Owl"];
/**
* Filter array items based on search criteria (query)
*/
const filteredOwls = (arr, query) => {
return arr.filter(el => el.toLowerCase().indexOf(query.toLowerCase()) !== -1)
}
console.log(filteredOwls(owls, 'Ba')) // ['Barn Owl', 'Barred Owl']
Filter Object from an Array of Object
const owls = [
{ name: 'Great horned owl', color: 'white' },
{ name: 'Barn Owl', color: 'brown' },
{ name: 'Snowy Owl', color: 'white' },
{ name: 'Barred Owl',color:'brown'}
]
const filteredOwls= owls.filter(owl=>owl.color==='white');
console.log(filteredOwls);
Output
[
{ name: 'Great horned owl', color: 'white' },
{ name: 'Snowy Owl', color: 'white' }
]
Remove Duplicates
We can use filter()
to remove the duplicates. On each iteration, we’ll use Array.indexOf()
to see if our item already exists.
If the returned index is smaller than the current index, that means an instance of item already exists.
Otherwise, we’ll return it to add it to the new array.
const owlsDuplicate = [
"Great horned owl",
"Barn Owl",
"Snowy Owl",
"Barred Owl",
"Great horned owl",
"Barn Owl"
];
const owlsUnique= owlsDuplicate.filter((owl, index) => owlsDuplicate.indexOf(owl) >= index);
console.log(owlsUnique);
output
[ 'Great horned owl', 'Barn Owl', 'Snowy Owl', 'Barred Owl' ]
We can also achieve this using Set
of ES6
as well.
However, a Set
is not an array, so we also need to pass our new set
through the Array.from()
method to convert it into one and will produce the same result.
const owlsUnique= Array.from(new Set(owlsDuplicate))
Conclusion
We have illustrated why and how we would use Javascript ES6
Array helper Array.filter()
and Array.map()
.
In future blog post we will talk about another beautiful Array helper Array.reduce()
in details.
Hope this post was useful. See you in next post.