【问题标题】:How to redundently remove duplicate elements within an array in node js如何在节点 js 中重复删除数组中的重复元素
【发布时间】:2020-11-27 03:51:55
【问题描述】:

我有一个问题,我需要过滤一组重复值。例如:[1,2,3,3,3,4] -> [1,2,3,4]

目前我已经编写了以下代码,但我认为没有足够的冗余。

const deduper = (arrayToDedupe) =>
  Object.values(
    Object.assign({}, [
      ...new Set(
        [...new Set(arrayToDedupe)]
          .filter((element, index, array) => index === array.indexOf(element))
          .reduce((acc, elementv2) => {
            if (acc.includes(elementv2)) {
              return acc;
            } else {
              acc.push(elementv2);
              return acc;
            }
          }, [])
          .map((elementv3, indexv3, arrayv3) => {
            if (indexv3 === arrayv3.indexOf(elementv3)) {
              return elementv3;
            } else {
              return undefined;
            }
          })
          .filter((x) => x)
      ),
    ])
  )
    .sort()
    .map((element, index, array) => {
      if (array[index + 1] === element) return undefined;
      return element;
    })
    .filter((x) => x);

有没有办法真正真正地确保返回的数组不会有任何重复。我需要添加更多链式数组方法吗?

【问题讨论】:

  • 您有您喜欢处理的数据示例吗?
  • 将它们放入Set,然后返回Array ;) 你就完成了(这适用于数字和基本数据类型,不包括对象)
  • 对于数据集,您可以将其视为如下数组:[1,2,3,3,3,4,5] 它也可以是字符串,例如:['never', 'rick', 'you', 'you', 'give', 'give', 'gonna', 'up' ]
  • 存在任何'冗余' 的意义并不清楚。你到底关心什么?哪种类型的输入数据需要让你的代码如此意大利面?
  • @memerson :给出的答案完美地解决了这两个用例。

标签: javascript node.js arrays duplicates


【解决方案1】:

您可以在 ecmascript6 中使用这一内衬解决方案:

const uniqueArray = [...new Set([1,2,3,3,3,4])];
console.log(uniqueArray);

集合是一种数据结构,它保存唯一的值,没有顺序。要知道的技巧是解构集合返回一个数组

【讨论】:

  • 这很好,老实说,如果我试图暴露 javascript 的 beauty,这是最好的方法,但我需要它尽可能冗余,有效地我们正在使用它作为上面提到的过滤方法之一。
  • @memerson :考虑给出一个不会被上述代码重复数据删除的数据示例,以了解您正在谈论的冗余
  • 感谢@Dominik Matis,他在 cmets 中首先回答了这个问题
猜你喜欢
  • 2013-05-20
  • 2013-03-23
  • 2017-08-12
  • 2018-02-14
  • 2011-12-31
  • 2018-11-10
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多