In his example Array.prototype.reduce, isn't this almost the same as just doing a foreach loop? I don't understand why doing this, it's pretty much the same number of lines.
let out = ["a", "b", "c", 1, 2, 3]
// Turn letters to upper case
.map(i => {
return typeof i === "string"
? i.toUpperCase()
: i;
})
// Add one to numbers
.map(i => {
return typeof i === "number"
? i + 1
: i;
})
// split letters and numbers up
.reduce((all, i) => {
typeof i === "string"
? all.letters.push(i)
: all.numbers.push(i);
return all;
}, { "letters": [], "numbers": [] });
// => { letters: ["A", "B", "C"], numbers: [2, 3, 4] }I wish that JavaScript's map/filter/reduce functions returned lazy iterators, like in Rust, so that code like this doesn't produce intermediate arrays. Does anyone know of a library that provides this?
All I really need now is Array.map, Array.reduce, Array.filter, Array.sort, Object.keys, Object.values.
Reduce is very powerful, you just have to get to know it.
Edit: this is how I'd use reduce in this case — https://news.ycombinator.com/item?id=14919636 — talk about line numbers
yes they are both ways of iterating over the array
> I don't understand why doing this
there's more than one way to skin a cat