取出不同元素
var arr1 = [0,1,2,3,4,5];
var arr2 = [0,4,6,1,3,9];
function getArrDifference(arr1, arr2) {
// filter(v, i, arr) => (当前元素的值,下标,当前元素属于的数组对象)
return arr1.concat(arr2).filter(function(v, i, arr) {
// 判断前后位置是否相同,相同就表示只有这一个值
return arr.indexOf(v) === arr.lastIndexOf(v);
});
}
console.log(getArrDifference(arr1,arr2));
当数组里是对象时:
var arr1 = [{id: 111, name: '第一个'},{id: 222, name: '第二个'},{id: 333, name: '第三个'}];
var arr2 = [{id: 111, name: '第一个'},{id: 333, name: '第三个'}];
remainArr = arr1.concat(arr2).filter((item, index, arr) => {
let numArr = arr.filter(value => {
return value.id === item.id
})
return numArr.length === 1
})
取出相同元素
var arr1 = [0,1,2,3,4,5];
var arr2 = [0,4,6,1,3,9];
function getArrEqual(arr1, arr2) {
let newArr = [];
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j] === arr2[i]){
newArr.push(arr1[j]);
}
}
}
return newArr;
}
console.log(getArrEqual(arr1, arr2));