2

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.

Shakti S
  • 351
  • 1
  • 3
  • 13

3 Answers3

8

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
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • that is just an approach to try to get a single loop solution, which is not, because of the doubeling of the items and the late use if the filtering for the second half of the new array, while you use the first to count the items. it looks more complicated than it should be. – Nina Scholz Nov 30 '18 at 15:01
0

We can achieve this using JavaScripts .filter() method.

const arr = [1,2,1.5,3,1.5,1];

const newArr = arr.filter(val => (arr.filter(v => v === val).length === 1));

console.log(newArr); // [ 2, 3 ]
Benni Russell
  • 354
  • 2
  • 7