skip to Main Content

Remove duplicates in an Array with numbers in string format?

I have snippet like how to remove duplicates from and array. I tried using filter method but its working with only numbers, But my array contains numbers in string format. So i am in confusion how to solve it.

// output = [1,2,3,4,5,6,7]

const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const result = arr1.filter((item, index) => arr1.indexOf(item) === index)

console.log(result);

// my result 
// [1, 2, "1", 3, 4, "3", 5, 6, 7, "5"]

// But output should be = [1,2,3,4,5,6,7]

Thanks in advance friends

Remove duplicates in an Array with numbers in string format?

I have snippet like how to remove duplicates from and array. I tried using filter method but its working with only numbers, But my array contains numbers in string format. So i am in confusion how to solve it.

// javascript

// output = [1,2,3,4,5,6,7]

const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];

const result = arr1.filter((item, index) => arr1.indexOf(item) === index)

//console.log(result);

// my result 

// [1, 2, "1", 3, 4, "3", 5, 6, 7, "5"]

// But output should be = [1,2,3,4,5,6,7]

Thanks in advance friends

    // output = [1,2,3,4,5,6,7] const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"]; const result = arr1.filter((item, 

index) => arr1.indexOf(item) === index) console.log(result); // my result 

// [1, 2, "1", 3, 4, "3", 5, 6, 7, "5"] 

// But output should be = [1,2,3,4,5,6,7]

Thanks in advance friends`

3

Answers


  1. You can use Number() to convert string to number and then filter it,below is a reference for you

    const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];
    
    const filterArr = (data) =>{
      data = data.filter((e, i) => data.indexOf(Number(e)) === i)
      return data
    }
    
    console.log(filterArr(arr1))
    Login or Signup to reply.
  2. You could just parse the strings as a number with parseInt(item) and then compare those. This code will parse strings as Int and then filter those.

    let arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];
    
    arr1 = arr1.map(m => parseInt(m));
    
    const result = arr1.filter((item, index) => arr1.indexOf(item) === index)
    
    console.log(result);
    Login or Signup to reply.
  3. Consider:

    const arr1 = [1,2,"1",3,2,4,"3",5,6,7,6,"5"];
    
    const result = [...new Set(arr1.map(Number))]
    
    console.log(result);

    What this does is:

    • convert everything to a number (map(Number))
    • turn an array into a Set (means no duplicates)
    • convert that set back into an array with [...]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search