【问题标题】:delete repeating consecutive values in array删除数组中重复的连续值
【发布时间】:2023-03-03 06:22:27
【问题描述】:

我有一个重复的数组。我正在寻找一种省略重复值的方法,即

[['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]

变成

[['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]

有什么干净的方法可以做到这一点?

【问题讨论】:

  • 你尝试了什么?所有数组都包含一个元素吗?
  • 我尝试了很多嵌套的 if()。这不是问答网站吗?
  • 使用arr.filter((item, index)=> arr.indexOf(item) === index);)。来源:filter duplicates in arrays - GeeksForGeeks
  • 为什么这个问题被关闭了?在我看来,这个问题非常集中。
  • @AliasCartellano 这在这里不起作用。

标签: javascript arrays


【解决方案1】:

这里有一个班轮:

const data = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];

console.log([...new Set(data.flat())].map(i => [i]))

【讨论】:

    【解决方案2】:
    • 定义一个Set 来存储数组元素
    • 使用Array#reduce,遍历列表。在每次迭代中,通过使用Array#join 连接其元素,将当前数组转换为字符串。然后,如果该值尚未在集合中,则将其添加并将当前数组推送到累积列表中。

    const arr = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];
    
    const set = new Set();
    const res = arr.reduce((list, e) => {
      const val = e.join();
      if(!set.has(val)) {
        set.add(val);
        list.push(e);
      }
      return list;
    }, []);
    
    console.log(res);

    【讨论】:

      【解决方案3】:

      console.log(Object.keys([
        ['cream'],
        ['cake'],
        ['cheese'],
        ['bread'],
        ['cream'],
        ['cake'],
        ['cheese'],
        ['bread'],
        ['butter']
      ].reduce((acc, val) => { // map to object
        acc[val] = true
        return acc;
      }, {})).map(key => [key])) // map object back to array

      【讨论】:

      • 这个,少粘
      猜你喜欢
      • 2022-01-12
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2019-11-09
      • 2017-09-20
      • 1970-01-01
      相关资源
      最近更新 更多