Remove duplicate

0

I have the following code in JavaScript and I would like to know where the error lies, I need to print non-repeated values or if you know some more effective way:

 var t1  = 2;
 var t2 = 2;
 var t3 = 3;

 var t4 = [t1,t2,t3];
 var t5 = t4.unique();
 console.log(t5);
    
asked by Rafael Pereira 25.01.2018 в 19:44
source

2 answers

4

The array in JavaScript does not have unique function.

If you are using ES5, you can do the following:

function unique(value, index, self) { 
   return self.indexOf(value) === index;
}

var t1 = 2;
var t2 = 2;
var t3 = 3;

var t4 = [t1,t2,t3];
var t5 = t4.filter(unique);
console.log(t5);

If you are using ES6, you can do the following:

var t1 = 2;
var t2 = 2;
var t3 = 3;

var t4 = [t1,t2,t3];
var t5 = t4.filter((value, index, self) => self.indexOf(value) === index);
console.log(t5);
    
answered by 25.01.2018 / 19:59
source
1

From ECMAScript 6 you can use the data structure: Set

[...new Set([1, 2, 2])]
    
answered by 25.01.2018 в 21:41