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
You can use Number() to convert string to number and then filter it,below is a reference for you
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.Consider:
What this does is:
map(Number)
)Set
(means no duplicates)[...]