DEV Community

Cover image for forEach() vs map() vs filter() methods
Joe Powell
Joe Powell

Posted on

forEach() vs map() vs filter() methods

map()
The map method returns new array of elements modified or not modified, below they are not modified.

let list = [1,2,3];
let mappedList = list.map((n)=> n); 
console.log(mappedList) // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

forEach()
The forEach method does not return, so with forEach we can iterate through an array and push it into another array or string then return that array or string.

let list_two = [1, 2, 3, 4, 5, 6];
let itemsForEached = [];
list_two.forEach(num => itemsForEached.push(num * 0))
console.log(itemsForEached) // [0, 0, 0, 0, 0, 0]

Enter fullscreen mode Exit fullscreen mode

filter()
filter returns an array filled with all the array elements that pass a test

const list = [...this.state.list];
const updatedList = list.filter(item => item.id !== id);
this.setState({ list: updatedList });
  or
const ages = [35, 37, 16, 49];
let filtered = ages.filter((age) return age >= 18 )
console.log(filtered) // [35, 37, 49]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)