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)); //[0, 4, 1, 3]
2、获取两个数组中不相同的元素
var arr1 = [0,1,2,3,4,5]; var arr2 = [0,4,6,1,3,9]; function getArrDifference(arr1, arr2) { return arr1.concat(arr2).filter(function(v, i, arr) { return arr.indexOf(v) === arr.lastIndexOf(v); }); } console.log(getArrDifference(arr1,arr2)); // [2, 5, 6, 9]
3、获取两个数组对象中相同的值
function getArrDifSameValue(arr1,arr2){ var result = []; for(var i = 0; i < arr2.length; i++){ var obj = arr2[i]; var id = obj.id; var isExist = false; for(var j = 0; j < arr1.length; j++){ var aj = arr1[j]; var n = aj.id; if(n == id){ isExist = true; break; } } if(isExist){ result.push(obj); } } return result; } var arr1 = [ {"id": "A"},{"id": "B"}]; var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}]; console.log(getArrDifSameValue(arr1,arr2));
4、获取两个数组对象中不相同的值
function getArrDifSameValue(arr1,arr2){ var result = []; for(var i = 0; i < arr2.length; i++){ var obj = arr2[i]; var id = obj.id; var isExist = false; for(var j = 0; j < arr1.length; j++){ var aj = arr1[j]; var n = aj.id; if(n == id){ isExist = true; break; } } if(!isExist){ result.push(obj); } } return result; } var arr1 = [ {"id": "A"},{"id": "B"}]; var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}]; console.log(getArrDifSameValue(arr1,arr2)); // [{"id": "C"}]
交流
我是老礼,公众号「进军全栈攻城狮」作者 ,对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!