skip to Main Content

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


  1. typeof returns a string, so you shouldn’t be comparing with the Number function. You can additionally simplify your code with Array#filter and spread syntax.

    let originalArray = [1,2,2,3,3, null,false,undefined];
    let res = [...new Set(originalArray.filter(x => typeof x === 'number'))];
    console.log(res);
    Login or Signup to reply.
  2. If you have a set, you don’t really need to keep the other array as well:

    const set = new Set(
      array.filter( item => typeof item === 'number' )
    );
    

    But if you need it to be converted back to an array, you can do that at the end:

    const newArray = Array.from(set);
    
    Login or Signup to reply.
  3. You can use filter to get only number values then dedupe it with spread syntax and a new Set

    • filter returns a new array of the filtered items
    • The Number method returns a Boolean value. In this case, it only filters numbers
    • Set creates an object of unique values so we need to wrap it in square brackets to cast it to an array.
    • The ... is spread syntax which extracts the object keys and inserts them into an index in the array
    const originalArray = [1,2,2,3,3, null,false,undefined];
    const filtered = originalArray.filter(item => Number(item))
    const unique = [...new Set(filtered)]
    
    console.log(unique) // [1, 2, 3]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search