繁体   English   中英

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

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

我在这里看到了许多类似的问题和答案,但没有一个直接回答这个问题。 对于每个数组元素,我都在寻找一种方法(使用 JavaScript)来检查它是否是数组中唯一的一个,或者是否至少有另一个。 例如:

const arr = [1,2,2]

寻找会返回的东西

true, false, false

当循环通过 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));

您可以分两次完成:

  • 构建一个包含每个元素计数的Map
  • 查找该Map每个元素

像这样:

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