Skip to content

Instantly share code, notes, and snippets.

@termi
Created February 22, 2025 18:37
Show Gist options
  • Save termi/4b448d09e0bc28ffe8170741a91cac58 to your computer and use it in GitHub Desktop.
Save termi/4b448d09e0bc28ffe8170741a91cac58 to your computer and use it in GitHub Desktop.
Get only unique values in array
function getOnlyUniqueValuesInArray(array) {
const arrayLen = array.length;
/** @type {Map<any, number>} */
const map = new Map();
for (let i = 0 ; i < arrayLen ; i++) {
const value = array[i];
map.set(value, map.getOrInsert(value, 0) + 1);
}
return array.filter(value => map.get(value) === 1);
}
console.assert(
getOnlyUniqueValuesInArray([10, 2, 3, 4, 5, 10, 6, 5, 0, 9, 2])
.join(',') === [3, 4, 6, 0, 9].join(',')
);
console.assert(
getOnlyUniqueValuesInArray(['10', 2, 3, 4, 5, 10, 'test', 5, 0, 9, 2])
.join(',') === ['10', 3, 4, 10, 'test', 0, 9].join(',')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment