Home >Web Front-end >JS Tutorial >What are the 5 ways to deduplicate arrays in JavaScript?
5 ways to remove duplicates from arrays: 1. Use the "[...new Set(arr)]" statement to remove duplicates; 2. Use the "Array.from(new Set(arr))" statement to remove duplicates. Duplication; 3. Use indexOf() to remove duplication; 4. Use includes() to remove duplication; 5. Use filter() to remove duplication.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to remove duplicates from an array
1.[...new Set(arr)]
const arr = [1, 2, 3, 2, 3]; [...new Set(arr)]; // [1, 2, 3]
Here is the Set object converted into an array through the expansion syntax of ES6;
2, Array.from(new Set(arr))
const arr = [1, 2, 3, 2, 3]; Array.from(new Set(arr)); // [1, 2, 3]
Due to The elements in Set are unique, whether they are original values or object references, so deduplication can be achieved by converting the array into a Set object.
The Array.from method can convert the Set object into an array
3. Use indexOf to remove duplicates
function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } var array = []; for (var i = 0; i < arr.length; i++) { if (array .indexOf(arr[i]) === -1) { array .push(arr[i]) } } return array; } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) // [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {…}, {…}] //NaN、{}没有去重
Create a new empty result array, for loop the original array, determine whether the current element exists in the result array, and skip if there are the same values. , if not the same, push into the array.
4. Use includes
function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } var array =[]; for(var i = 0; i < arr.length; i++) { if( !array.includes( arr[i]) ) {//includes 检测数组是否有某个值 array.push(arr[i]); } } return array } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}] //{}没有去重
5. Use filter
function unique(arr) { return arr.filter(function(item, index, arr) { //当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素 return arr.indexOf(item, 0) === index; }); } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) //[1, "true", true, 15, false, undefined, null, "NaN", 0, "a", {…}, {…}]
[Related recommendations: javascript learning tutorial 】
The above is the detailed content of What are the 5 ways to deduplicate arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!