What is the difference between filter and map?
They both return a new array.
1. Map
The map function returns the same number of elements as present in the original array but the value of elements will be transformed in some way.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = items.map((item) => {
return item*item;
})
console.log(result);
// [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
2. Filter
On the other hand, the filter function can return fewer or more elements than the original array but the value of the original elements will not change.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = items.filter((item) => {
return item > 5;
})
console.log(result);
// [ 6, 7, 8, 9, 10 ]
BY Best Interview Question ON 09 Aug 2022