当前位置:网站首页>JS array de duplication, removing the same value

JS array de duplication, removing the same value

2022-06-23 03:35:00 It workers

ES5 Realization

JavaScript 1.6 / ECMAScript 5  You can use native methods filter To achieve array de duplication .

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

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

Native filter Method will loop through the array , And pass the callback parameter to onlyUnique function .

onlyUnique It will check whether the callback value appears for the first time , If not , Will not be generated into the array .

This method does not require any additional libraries , for example jQuery or prototype.js.

This method is also applicable to mixed type arrays .

For not supporting filter or indexOf Old browser for method , We can consider give up .

Make fun of , You can refer to it MDN file , Find out about filter and indexOf Compatible solutions .

ES6

ES6 have access to Set To achieve array de duplication , Compared with ES5 The code will be simpler .

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201180942238528.html