簡體   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