Home >Web Front-end >JS Tutorial >How to remove duplicates when merging multiple arrays in JS
This time I will show you how to remove duplicates in JS when merging multiple arrays. What are the precautions for deduplication in JS when merging multiple arrays? The following is a practical case, let's take a look.
var arr1 = ['a','b']; var arr2 = ['a','c','d']; var arr3 = [1,'d',undefined,true,null]; //合并两个数组,去重 var concat_ = function(arr1,arr2){ //不要直接使用var arr = arr1,这样arr只是arr1的一个引用,两者的修改会互相影响 var arr = arr1.concat(); //或者使用slice()复制,var arr = arr1.slice(0) for(var i=0;i<arr2.length;i++){ arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0; } return arr; } console.log(concat_(arr1,arr2));
Run result:
##
var arr1 = ['a','b']; var arr2 = ['a','c','d']; var arr3 = [1,'d',undefined,true,null]; //合并多个数组,去重 var concat = function(arr1,arr2,arr3){ if(arguments.length <= 1){ return false; } var concat_ = function(arr1,arr2){ var arr = arr1.concat(); for(var i=0;i<arr2.length;i++){ arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0; } return arr; } var result = concat_(arr1,arr2); for(var i=2;i<arguments.length;i++){ result = concat_(result,arguments[i]); } return result; } console.log(concat(arr1,arr2,arr3));Run result:
##
//合并多个数组,去重,排序 var arr1 = [1,6,4,0]; var arr2 = [8,20,7,4.5]; var arr3 = [6,0,7,90,2]; var concat = function(arr1,arr2,arr3){ if(arguments.length <= 1){ return false; } var concat_ = function(arr1,arr2){ var arr = arr1.concat(); for(var i=0;i<arr2.length;i++){ arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0; } return arr; } var result = concat_(arr1,arr2); for(var i=2;i<arguments.length;i++){ result = concat_(result,arguments[i]); } //排序 function sortNumber(a,b){ return a - b; } return result.sort(sortNumber); } console.log(concat(arr1,arr2,arr3));Run result:
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
React props and state attribute practical case explanationvue-simplemde to make image drag and drop, PasteThe above is the detailed content of How to remove duplicates when merging multiple arrays in JS. For more information, please follow other related articles on the PHP Chinese website!