javascript - 获取嵌套数组/对象的数组中的所有唯一值(删除重复项)

标签 javascript arrays node.js unique

我知道唯一数组有很多答案

但他们无法处理数组数组


我想要的是

源数组

[
    1,
    0,
    true,
    undefined,
    null,
    false,
    ['a', 'b', 'c'],
    ['a', 'b', 'c'],
    ['a', 'c', 'b'],
    { a: { b: 2 } },
    { a: { b: 2 } },
    { a: { b: 3 } },
    { a: { b: undefined } },
    { a: {  } },
    { a: { b: 3, c: undefined } },
]

返回

[
    1,
    0,
    true,
    undefined,
    null,
    false,
    ['a', 'b', 'c'],
    ['a', 'c', 'b'],
    { a: { b: 2 } },
    { a: { b: 3 } },
    { a: { b: undefined } },
    { a: {  } },
    { a: { b: 3, c: undefined } },
]
  • arr-unique可以处理对象[],但不能处理数组数组
  • 设置不能太

失败代码

console.log(array_unique(data));

console.log([...new Set(data)]);

console.log(data.filter(function (el, index, arr)
{
    return index == arr.indexOf(el);
}));

====================

更新

我为此创建了一个模块 array-hyper-unique ,但没有使用 json stringify,因为当 valuse 为正则表达式时它有一个错误

最佳答案

一种简单的方法是对数组和对象进行stringify以识别重复项:

const input = [
    1,
    true,
    ['a', 'b', 'c'],
    ['a', 'b', 'c'],
    { a: { b: 2 } },
    { a: { b: 2 } },
    { a: { b: 3 } },
    { a: { b: 3, c: undefined } },
];

const outputSet = new Set();
const stringifiedObjs = new Set();
input.forEach(item => {
  if (typeof item !== 'object') outputSet.add(item);
  else {
    // replace undefineds with something, else they'll be ignored by JSON.stringify:
    const stringified = JSON.stringify(
      item,
      (k, v) => v === undefined ? 'undefined-value' : v
    );
    if (!stringifiedObjs.has(stringified)) {
      outputSet.add(item);
      stringifiedObjs.add(stringified)
    }
  }
});
console.log([...outputSet]);

关于javascript - 获取嵌套数组/对象的数组中的所有唯一值(删除重复项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50597784/

相关文章:

javascript - 如何使用 MongoDB 和 Nodejs 创建用户角色/权限?

javascript - 日期范围选择器为 24 小时范围创建错误的时间值

php - 将 php 代码转换为 Objective-C

javascript - 将字符串转换为 JSON

javascript - 关于 Ember 中的自定义构建

javascript - 如何在 Javascript 中创建 JWT exp 样式日期

javascript - 在 Rally SDK 1.32 中,DropDown 选项在 IE 浏览器中无法正常工作

c++ - 如何实现一个以其索引为 2 开头的数组

node.js - Node js Cassandra 驱动程序 - 配置重试策略

javascript - 在循环中获取数据