我有两个名为arr
和ar
的数组。假设ar
有7个元素,arr
有6个元素。如果元素在两者中都相同,我想删除一个元素,否则将其分配给一个新变量。到目前为止我有这个:
var arr = new Array(); // Elements are 65,66,67,68,69,70
var newID = new Array();
var ar = new Array(); // 64,65,66,67,68,69,70
if (ar.length != arr.length) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < ar.length; j++) {
if (arr[i] == ar[j]) {
delete ar[i];
arr.splice(i, 1);
break;
}
newID = ar[i];
}
}
for (var i = 0; i < ar.length; i++) {
newID = ar[i];
}
这不能正常工作,因为它会与未找到的值进行比较。请帮我纠正。
答案 0 :(得分:2)
您可以尝试以下操作:
var arr = [1, 2, 3, 4, 5, 6, 7];
var ar = [2, 4, 6, 8, 10];
var newID = [];
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < ar.length; j++){
if(arr[i] == ar[j]){
newID.push(arr[i]);
arr.splice(i, 1);
ar.splice(j, 1);
break;
}
}
}
alert(arr);
alert(ar);
alert(newID);
答案 1 :(得分:1)
我会给你以下解决方案。
var ar = [1,2,3,4,5,6,7];
var arr = [3,6,7,8,9,2];
//ES5
var mergedArray = ar.concat(arr);
var newId = [];
for(var i=0;i<mergedArray.length;i++){
var id = mergedArray[i];
if(newId.indexOf(id) !== -1) continue;
newId.push(id);
}
//or smartter
var newId = ar.concat(arr).filter(function(id, pos, self) {
return self.indexOf(id) === pos;
});
//or ES6
var mergedArray = ar.concat(arr);
var newId = [];
for(let id of mergedArray){
if(newId.indexOf(id) !== -1) continue;
newId.push(id);
}
//or smarter ES6
var newId = ar.concat(arr).filter((id, pos, self) => self.indexOf(id) === pos);
选择权在你手中。 :)
答案 2 :(得分:1)
此处还有一个使用reduce
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [1, 3, 5, 7, 9];
var result = arr1.reduce(function (prev, value) {
var isDuplicate = false;
for (var i = 0; i < arr2.length; i++) {
if (value == arr2[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
prev.push(value);
}
return prev;
}, []);
alert(JSON.stringify(result.concat(arr2)));
&#13;
<强> EDITED 强>
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [1, 3, 5, 7, 9];
arr2 = arr2.reduce(function (prev, value) {
var isDuplicate = false;
for (var i = 0; i < arr1.length; i++) {
if (value == arr1[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
prev.push(value);
}
return prev;
}, []);
alert(JSON.stringify(arr2));
&#13;
答案 3 :(得分:0)
我只想添加一个js库 - lodash
var _ = require('lodash');
var array1 = [1,2,3,4,5];
var array2 = [3,1,5];
_.difference(array1,array2)
// returns [ 2, 4 ]
答案 4 :(得分:0)
var arr = [1, 2,2, 3, 4, 5, 6, 7];
var ar = [2, 4, 6, 8, 10];
var combinearray = [...arr,...ar]
var newArr = new Set(combinearray);
console.log(newArr)