I have an array in javascript like this
var arr = [1,2,1.5,3,1.5,1];
I want to remove all duplicate values from the array,So my output will be like
[2,3]
I can do it using loops.I have posted this question here because I need a fasted way to get it done.
You could check the first and last index of the value and take it if the index is the same.
var array = [1, 2, 1.5, 3, 1.5, 1],
ones = array.filter((v, _, a) => a.indexOf(v) === a.lastIndexOf(v));
console.log(ones);
An approach with a Map.
It works with a map by taking the opposite of the check if the map has already one entry with the given value.
For any following same values, the entry changes to
false, which later omits these values.
var array = [1, 2, 1.5, 3, 1.5, 1, 1, 1],
map = array.reduce((m, v) => m.set(v, !m.has(v)), new Map),
ones = array.filter(Map.prototype.get, map);
console.log(ones);
console.log([...map]); // just for checking the values
I tried this new approach to get only non-repeated values using just Array.filter... Fellow users comments are welcome if you feel it's better performance wise or not.
var arr = [1,2,1.5,3,1.5,1]
let tmp = {}
let res = [...arr, ...arr].filter((d, i) => {
tmp[d] = (tmp[d] || 0) + 1
return i > arr.length - 1 && tmp[d] == 2
})
console.log(res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With