How do I make an array with unique elements (i.e. remove duplicates)?

Viewed 83532

I have this code:

var ar = [10,7,8,3,4,7,6];

function isin(n,a){
  for (var i=0;i<a.length;i++){
    if (a[i]== n) {
      var b = true;
      return b;
    } else {
      var c = false;
      return c;
   }
  }
}

function unique(a){
  var arr = [];
  for (var i=0;i<a.length;i++){
    if (!isin(a[i],arr)){
      arr.push(a[i]);
    }
  }

 return arr;
}

alert(unique(ar));

In this code, I try to create new unique array (without duplicates) out of the original one. But I still get the original array! Where's my mistake?

18 Answers

In addition to usage of filter respond by Josh Mc, you can make it crazy shorter in es6 with arrow function utility;

const a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((it, i, ar) => ar.indexOf(it) === i);
// unique = [1, 2, 3]

You can use the Spread Operator and take advantage of the uniqueness offered by Sets.

const ar = [10, 7, 8, 3, 4, 7, 6];
const arUnique = [...new Set(ar)];

I've done a similar search, I found this answer really good:

Unique values in an array [duplicate]

You can re-use those function on other code. This is also good approach where it is compatible with many browsers.

Cheer.

Simplest version I know: Array.from(new Set(duplicateArray))

Expanding on Jamiecs' answer above, here's an Array.prototype. of the same.

var arr = [1, 1, 1, 2, 5, 6, 4, 5 , 1];

Array.prototype.uniqueArr = function() {
var arr = [];
for (var i=0;i<this.length;i++) {
  if ( arr.indexOf(this[i]) == -1 ) {
    arr.push(this[i]);
  }
}
return arr
}

var arr = arr.uniqueArr();

console.log(arr);

Using Filter Function

const getUnique = (arr) => {
  return arr.filter((val, i, _self) => {
  return _self.indexOf(val) === i;
 });
}
let arr = [1,2,1,3,4,2];
console.log(getUnique(arr)); // [ 1, 2, 3, 4 ]

If you are okay with/already using lodash, then uniq function of Array is the one you are looking for.

_.uniq([2, 1, 2]);
// => [2, 1]
Related