从数组的数组中获取唯一值

7
我有以下数组。
let arr =   [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
]

我希望从这个数组中获取唯一的值。所以我期望我的结果像这样
[
  [
    "s1@example.com",
    "s2@example.com",
    "s3@example.com"
  ]  
]

我使用了数组去重函数,但无法得到结果。

var new_array = arr[0].concat(arr[1]);
var uniques = new_array.unique();

如果我有两个索引,那么这个方法是可行的,但是如果有多个索引呢?


2
这个 .unique() 方法是不是不存在了?试试使用 .writeCodeForMe() 方法。 - zer00ne
2个回答

15
你可以使用.flat()来压平你的数组,然后使用Set获取其唯一值。
演示:

let arr =   [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
]

let arr2 = [...new Set(arr.flat(1))];
console.log(arr2)


0

你可以利用Set,它会自动处理重复项,你可以在这里找到更多关于Sets的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

由于许多解决方案都使用flatSet,因此这里提供了一种使用函数生成器来实际展平数组的解决方案,只要它们不是数组(否则,它会递归地展平它们),就会产生项目。

let arr = [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
];

function* flatten(array) {
  for (var item of array) {
    if (Array.isArray(item)) {
      yield* flatten(item)
    }
    else yield item;
  }
}

const set = [...new Set(flatten(arr))];
console.log('set is', set);

如果您不想使用Set,这里有一个无需Set的解决方案,通过创建一个新数组并推送项目,只要它们不存在。

let arr = [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
];

function* flatten(array) {
  for (var item of array) {
    if (Array.isArray(item)) {
      yield* flatten(item)
    }
    else yield item;
  }
}

let unique = [];
for (const item of flatten(arr)) {
  if (unique.indexOf(item) === -1) unique.push(item);
}
console.log(unique);


如果所有的数组方法都能存在于迭代器上,那真是太好了... - Jonas Wilms

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接