Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best approach to remove duplicate values from an array in native javascript

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.

like image 914
Shakti S Avatar asked Nov 19 '25 11:11

Shakti S


2 Answers

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
like image 159
Nina Scholz Avatar answered Nov 21 '25 23:11

Nina Scholz


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)
like image 44
Nitish Narang Avatar answered Nov 22 '25 00:11

Nitish Narang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!