How get unique items in array Javascript
Problem: We have a array of numbers. Calculate unique numbers in array
Solution 1:
const array = [1, 2, 1, 3, 2, 4, 5, 5]
const uniqueNumberChecker = {}
const uniqueNumbers = []
for(let i = 0; i <= array.length; ++i) {
if (!uniqueNumberChecker[array[i]]) {
uniqueNumbers.push(array[i])
uniqueNumberChecker[array[i]] = true
}
}
// Result uniqueNumbers
In above we use object to check number is exist of not, we can use Map type also
Solution 2:
const array = [1, 2, 1, 3, 2, 4, 5, 5]
const uniqueNumberSet = new Set(array)
const uniqueNumbers = Array.from(uniqueNumberSet)
// Or
const uniqueNumbers = [...uniqueNumberSet]
Two solutions have time complexity is O(n*logn)