设置不在另一个数组中的元素数组

时间:2022-05-29 23:33:59

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?

甚至更好,这两个数组的最佳方式是什么,计算/迭代次数较少?

1 个解决方案

#1


2  

With one iteration:

一次迭代:

const {even, odd} = numbers.reduce((a, b) => (a[b % 2 === 0 ? 'even' : 'odd'].push(b), a) , {even: [], odd: []});

#1


2  

With one iteration:

一次迭代:

const {even, odd} = numbers.reduce((a, b) => (a[b % 2 === 0 ? 'even' : 'odd'].push(b), a) , {even: [], odd: []});