简体   繁体   中英

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. For example:

const arr = [1,2,2]

looking for something that will return

true, false, false

when looping through 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
  • look up each element in that 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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