acidzombie24 acidzombie24 - 9 months ago 66
Javascript Question

Iterate an array using two or more elements at a time

In short I was wondering if there was a way to do this in a more straight forward way. The problem with chunk I feel is I got to create a new array then I have to map it so I get just the first value. Is there a way I can loop 2 items at a time?

a = [5, 1, 6, 0, 8, 0, 9, 1, 10, 0]
b = _.chunk(a, 2)
zeros = b.filter(s=> s[1] == 0).map(s=>s[0])
ones = b.filter(s=> s[1] == 1).map(s=>s[0])

Alternative I'd like

_.MyEach(a, 2, (l, m)=> if(m==0) zero.push(l); else ones.push(l))

OR (less likely but acceptable)

zeros = _.MyFilter(a, 2, (l, m) => if(m==0) l else null);
ones = _.MyFilter(a, 2, (l, m) => if(m==1) l else null);

Answer Source

You can do without the _ library altogether, in this case using ES6 syntax which allows decomposing the 2D array into individual variables in one hit:

var [zeroes, ones] = a.reduce(
    (p, c, i, a) => i % 2 ? (p[c].push(a[i - 1]), p) : p, [[], []]);

This iterates over the array once, and for the odd elements it looks at the zero or one contained therein, and drops the preceding value into either the [0] or [1] element of the seed array.