简体   繁体   English

如何检查数组元素是否是数组中唯一的值?

[英]How to check if array element is the only one of its value in array?

I've seen many similar questions and answers here but none that directly answered this question.我在这里看到了许多类似的问题和答案,但没有一个直接回答这个问题。 For each array element I'm looking for a way (with JavaScript) to check if it's the only one of its kind in the array, or if there is at least one other of it.对于每个数组元素,我都在寻找一种方法(使用 JavaScript)来检查它是否是数组中唯一的一个,或者是否至少有另一个。 For example:例如:

const arr = [1,2,2]

looking for something that will return寻找会返回的东西

true, false, false

when looping through arr.当循环通过 arr.

 const arr = [1, 2, 2]; console.log(arr.map(item => arr.indexOf(item) === arr.lastIndexOf(item)));

const arr = [1, 2, 2];
arr.map(item => arr.indexOf(item) === arr.lastIndexOf(item));

You can do it in two passes:您可以分两次完成:

  • build a Map containing the count of each element构建一个包含每个元素计数的Map
  • look up each element in that Map查找该Map每个元素

Like so:像这样:

const getCounts = iterable => {
    const counts = new Map();

    for (const x of iterable) {
        counts.set(x, (counts.get(x) ?? 0) + 1);  // use || for ES6 compat
    }

    return counts;
};

const arrCounts = getCounts(arr);
arr.map(x => arrCounts.get(x) === 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM