TIL how NOT to loop through arrays
POSTED ON:
TAGS: javascript arrays
Iterating an array to build another one #
If you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.
// Don't do this:
const numbers = [1,2,3,4,5];
let doubled = [];
numbers.forEach((n, i) => { doubled[i] = n * 2 });
// Do this:
const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);
Summing the array of numbers #
You want to sum an array of numbers, you should use the reduce method.
const numbers = [1,2,3,4,5];
// Don't do this
const sum = 0;
numbers.forEach(num => {
sum += num;
});
// Instead
const sum = numbers.reduce((total, n) => total + n, 0);
Via https://stackoverflow.com/a/3010848/4096078
Related TILs
Tagged: javascript