Map, Filter, and Reduce are powerful array methods that are definitely worth learning! This is a super-quick primer on each method.
map: return array where each element is transformed as specified by the function
const arr = [1, 2, 3, 4, 5, 6];
const mapped = arr.map(el => el + 20);
console.log(mapped);
// [21, 22, 23, 24, 25, 26]
filter: return array of elements where the function returns true
const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter(el => el === 2 || el === 4);
console.log(filtered);
// [2, 4]
reduce: accumulate values as specified in function
const arr = [1, 2, 3, 4, 5, 6];
const reduced = arr.reduce((total, current) => total + current, 0);
console.log(reduced);
// 21
More arguments
Note that this is the most basic use of the map
, filter
, and reduce
methods and the functions passed to them can take additional arguments. In other words, please treat this post as a basic introduction!
Learn More
I put out free email newsletters with JavaScript tips on a weekly basis and would love to put some in your inbox! Sign up here.
Top comments (0)