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:
Map
containing the count of each elementMap
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.