根据条件将列表分成两个新列表的最佳方法

Zol*_*ére 2 javascript

我正在寻找基于条件将数组拆分为两个新数组的好方法。假设我们有一个包含相同结构对象的列表,该对象有一个 bool 属性,我们称之为条件,我们想要两个只有相同条件元素的新列表。

const cont1 = myArray.filter((el) => el.condition)
const cont2 = myArray.filter((el) => !el.condition)
Run Code Online (Sandbox Code Playgroud)

我猜这可以工作,但我想知道是否有更好的单次迭代版本。

Cer*_*nce 5

一种选择是使用reduce,它将在对数组的一次迭代中在功能上分离所有项目:

const myArray = [
  { condition: true },
  { condition: true },
  { condition: false },
]
const [cont1, cont2] = myArray.reduce(([cont1, cont2], item) => {
  (item.condition ? cont1 : cont2).push(item);
  return [cont1, cont2];
}, [[], []]);

console.log('cont1: ', cont1);
console.log('cont2: ', cont2);
Run Code Online (Sandbox Code Playgroud)

或者,功能较少但可能更具可读性,您可以.push使用外部变量:

const myArray = [
  { condition: true },
  { condition: true },
  { condition: false },
];
const cont1 = [];
const cont2 = [];
myArray.forEach((item) => {
  (item.condition ? cont1 : cont2).push(item);
});

console.log('cont1: ', cont1);
console.log('cont2: ', cont2);
Run Code Online (Sandbox Code Playgroud)