Anyul Rivas Anyul Rivas - 1 year ago 77
Javascript Question

Set an array of elements not in another array

I have an array of numbers

const numbers = [12,37,5,42,8,3];

And i want to set an array of even numbers from my initial array

const even = numbers.filter((number) => {return number % 2==0; });

I new a method to get the odd numbers by extracting the even numbers out of the initial array.

or even better, what's the optimal way to the two array with less computation/iterations?

Answer Source

With one iteration:

const {even, odd} = numbers.reduce((a, b) => (a[b % 2 === 0 ? 'even' : 'odd'].push(b), a) , {even: [], odd: []});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download