What are the benefits of using array methods (forEach, map, etc.) over loops?
How does .map() work?
const strings = ['42', '23', '15', '2']; const numbers = strings.map(s => Number(s)); // [42, 23, 15, 2] (notice the lack of quote ')
How does .filter() work?
const numbers = [4, 2, 1, 3, 5, 8];
const evens = numbers.filter(num => num % 2 === 0); // [4, 2, 8]How does .reduce() work?
const numbers = [2,5,7]; const sum = numbers.reduce((sum, number) => sum + number, 0);
const animals = ['cat', 'dog']; const joined = animals.reduce((res, animal) => res + ', ' + animal)); // no initial value
const joined = animals.reduce((res, animal) => res + ‘, ‘ + animal, ‘’); // with initial value
How can implement filter by using reduce?
const filter = (array = [], filterFn) => {
const result = array.reduce((acc, el, index, arr) => {
if (filterFn(el, index, arr)) {
acc.push(el);
}
return acc;
}, []);
return result;
};
const filtered = filter([2, 6, 5, 8, 10], (el) => el > 5); console.log(filtered); // [ 6, 8, 10 ]
How can implement mapby using reduce?
const map = (array = [], mapFn) => {
const result = array.reduce((acc, el, index, arr) => {
acc.push(mapFn(el, index, arr));
return acc;
}, []);return result;
};
console.log(map([1, 2, 3], (el) => el * 2)); // [ 2, 4, 6 ]