Assume I have an array like this arr = [1,2,2,3,3,null,false,undefined]
how to remove duplicates and other data types and keep only unique numbers ? I have tried below `
let originalArray = [1,2,2,3,3, null,false,undefined];
let newArray = [];
let set = new Set();
for (let i = 0; i < originalArray.length; i++) {
if(!set.has(originalArray[i]) && typeof originalArray[i] === Number ) {
newArray.push(originalArray[i]);
set.add(originalArray[i]);
}
}
console.log(newArray);
the above code output comes as empty array.
I have tried using typeof but it does not work. Is there any other way or approach to this
3
Answers
typeof
returns a string, so you shouldn’t be comparing with theNumber
function. You can additionally simplify your code withArray#filter
and spread syntax.If you have a set, you don’t really need to keep the other array as well:
But if you need it to be converted back to an array, you can do that at the end:
You can use
filter
to get only number values then dedupe it with spread syntax and a newSet
...
is spread syntax which extracts the object keys and inserts them into an index in the array