How to use map() and filter() methods on the same array in JavaScript?
All about map, filter and reduce methods with examples!
map
, filter
and reduce
methods were introduced in ES5. These methods are applied to arrays.
✨Map()
map
method in javascript returns a new array depending on the condition applied to the current array for each element. It doesn't change the original array.
Syntax: newArray = (originalArray).map(callback);
Here, callback
is a function that takes 3 parameters - currentValue
, currentValueIndex
, originalArray
. The last two parameters are optional.
Let's say we have an array of objects - nameArray
and we want to modify each object by adding a new field - id
.
let nameArray = [
{firstName: "Walter", lastName: "White"},
{firstName: "Tony", lastName: "Stark"}
]
let count=1;
newNameArray = nameArray.map((currentObject) => {
// currentObject = {firstName: "Walter", lastName: "White"}
return {id: count++, ...currentObject}; // return modified object
});
console.log(newNameArray);
// OUTPUT:-
// [
// {id: 1, firstName: "Walter", lastName: "White"},
// {id: 2, firstName: "Tony", lastName: "Stark"}
// ]
✨Filter()
filter
method in javascript filters out elements from the original array which doesn't fulfill the condition provided by a function. This method also returns a new array and doesn't change the original array.
Syntax: newArray = (originalArray).filter(callback);
Same as map()
, callback
takes 3 parameters - currentValue
, currentValueIndex
, originalArray
. The last two parameters are optional.
Let's say we have an array of objects nameArray
and we want to filter out objects with even id
.
let nameArray = [
{id: 1, firstName: "Walter", lastName: "White"},
{id: 2, firstName: "Tony", lastName: "Stark"},
{id: 3, firstName: "Rebecca", lastName: "Pearson"}
]
newNameArray = nameArray.filter((currentObject) => {
// currentObject = {id:1, firstName: "Walter", lastName: "White"}
return currentObject.id%2 != 0;// returns true, hence not removed
});
console.log(newNameArray);
// OUTPUT:-
// [
// {id: 1, firstName: "Walter", lastName: "White"},
// {id: 3, firstName: "Rebecca", lastName: "Pearson"}
// ]
✨Reduce()
reduce
method in javascript runs a "reducer" callback function on each element of an array. It does not change the original array.
Syntax: newArray = originalArray.reduce(callback, initialValue);
callback: function(previousValue, currentValue, currentIndex, OriginalArray)
Here, the callback
function takes 4 parameters - previousValue
, currentValue
, currentIndex
and OriginalArray
. The last two are optional.
If initialValue
(optional) is not given then the first element is assigned to previousValue
and the iteration starts from the next element. If we supply initialValue
then it will be assigned to previousValue
.
✨Ways to use map and filter methods on the same array:-
Let's say, from the above example, we want to get all names as firstName+lastName
for odd id
.
We can simply apply
map
andfilter
methods separately using extra arrays.let nameArray = [ {id: 1, firstName: "Walter", lastName: "White"}, {id: 2, firstName: "Tony", lastName: "Stark"}, {id: 3, firstName: "Rebecca", lastName: "Pearson"} ] // filters out objects with even id filteredArray = nameArray.filter(currentObject => currentObject.id%2 != 0) modifiedArray = filteredArray.map(currentObject => currentObject.firstName+" "+currentObject.lastName) console.log(filteredArray); console.log(modifiedArray); // OUTPUT: // [ // { id: 1, firstName: 'Walter', lastName: 'White' }, // { id: 3, firstName: 'Rebecca', lastName: 'Pearson' } // ] // [ 'Walter White', 'Rebecca Pearson' ]
Simplify the above code by removing the use of another array to store values.
nameArray.filter(currentObject => currentObject.id%2 != 0)
will return an array with filtered objects which will then be used bymap
method.let nameArray = [ {id: 1, firstName: "Walter", lastName: "White"}, {id: 2, firstName: "Tony", lastName: "Stark"}, {id: 3, firstName: "Rebecca", lastName: "Pearson"} ] modifiedArray = nameArray.filter(currentObject => currentObject.id%2 != 0).map(currentObject => currentObject.firstName+" "+currentObject.lastName) console.log(modifiedArray); // OUTPUT: // [ 'Walter White', 'Rebecca Pearson' ]
Use
reduce
method.let nameArray = [ {id: 1, firstName: "Walter", lastName: "White"}, {id: 2, firstName: "Tony", lastName: "Stark"}, {id: 3, firstName: "Rebecca", lastName: "Pearson"} ] reducedArray = nameArray.reduce((filteredArray, currentObject) => { if (currentObject.id%2 != 0) { let modifiedValue = currentObject.firstName+" "+ currentObject.lastName filteredArray.push(modifiedValue); } return filteredArray; }, []); // initialvalue as empty array console.log(reducedArray) // OUTPUT: // [ 'Walter White', 'Rebecca Pearson' ]
For
previousValue
, we have takenfilteredArray
as a variable and assigned[]
to make it an array. Every time thecurrentObject
satisfies the condition, it is pushed to thefilteredArray
.The returned value is again assigned tofilteredArray
and the same goes on for the other element.