【问题标题】:filter array and remove the filtered data from array in JavaScript [duplicate]过滤数组并从JavaScript中的数组中删除过滤后的数据[重复]
【发布时间】:2018-12-07 17:01:45
【问题描述】:

假设我有一个带有数字的数组

const nums = [0, 1, 2, 3, 4, 5];

我想得到所有小于 3 的数字

const targetNums = nums.filter(x => x < 3);

如何从我的原始数组中删除这些过滤后的数字?

当我过滤数字时,nums 应该保留

nums = [3, 4, 5];

我想过这样的事情

const targetNums = nums.filter(x => x < 3);
nums.reduce(x => x < 3);

但我认为这不是干净的代码。

【问题讨论】:

  • 为什么需要从原始数组中删除数字?只需使用.filter 返回的副本即可。 .reduce 也不会改变原始数组。

标签: javascript arrays


【解决方案1】:

你确实可以在不需要filter的情况下使用reduce

const nums = [0, 1, 2, 3, 4, 5];

console.log(
  nums.reduce((acc, x) => x < 3 ? acc.concat(x) : acc, [])
);

【讨论】:

  • 不鼓励重复问题。
  • 这如何回答这个问题? Reduce 不会改变原始数据。
  • 如何从数组中删除项目?
  • 那么应该是nums.reduce((acc, x) =&gt; x &gt;= 3 ? acc.concat(x) : acc, [])
  • 同意错过原始数组要自己编辑
猜你喜欢
  • 2020-11-24
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多