Created
February 22, 2025 18:37
-
-
Save termi/4b448d09e0bc28ffe8170741a91cac58 to your computer and use it in GitHub Desktop.
Get only unique values in array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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