可以使用es7數(shù)組新增的includes方法。遍歷數(shù)組a, 然后看數(shù)組b是否includes闸天。
functionisEquals(a, b){returnJSON.stringify(a.sort()) ===JSON.stringify(b.sort());}
改進(jìn)算法
缺陷:比較數(shù)組的時(shí)候必須按順序相等暖呕,因?yàn)閿?shù)級(jí)里的 object 沒法排序
constcompare =(() =>{functioncompareArray(a, b){console.log("array", a, b);if(a.length !== b.length) {returnfalse;? ? ? ? }constlength = a.length;for(leti =0; i < length; i++) {if(!compare(a[i], b[i])) {returnfalse;? ? ? ? ? ? }? ? ? ? }returntrue;? ? }functioncompareObject(a, b){console.log("object", a, b);constkeya =Object.keys(a);constkeyb =Object.keys(b);if(keya.length !== keyb.length) {returnfalse;? ? ? ? }returnkeya.every(key=>{if(!compare(a[key], b[key])) {returnfalse;? ? ? ? ? ? }returntrue;? ? ? ? });? ? }functioncompare(a, b){if(a === b) {returntrue;? ? ? ? }if(typeofa !==typeofb || a ===null|| b ===null) {returnfalse;? ? ? ? }if(Array.isArray(a)) {if(!Array.isArray(b)) {returnfalse;? ? ? ? ? ? }returncompareArray(a, b);? ? ? ? }if(typeofa ==="object") {returncompareObject(a, b);? ? ? ? }console.log("value", a, b);returnfalse;? ? }returncompare;})();varaa = [{Name:"YuanXP",Id:9}, {Name:"YuanX",Id:9}];varbb = [{Name:"YuanXP",Id:9}, {Id:9,Name:"YuanX"}];varcc = [{Name:"YuanXP",Id:19}, {Id:9,Name:"YuanX"}];console.log(compare(aa, bb));console.log(compare(aa, cc));
function isEquals(a, b) {
let_a= a.sort();let_b= b.sort();return JSON.stringify(_a) === JSON.stringify(_b);
}
你好,貌似compare缺少typeof相等 值不等時(shí)候的判斷
var aa = [{Name:"YuanXP",Id:[9] }, {Name:"YuanX",Id:9}];var bb = [{Name:"YuanXP",Id:[10]}, {Id:9,Name:"YuanX"}];
http://underscorejs.org/#differencedifference_.difference(array, *others)Similar to without, but returns thevaluesfromarraythat arenotpresentinthe otherarrays._.difference([1,2,3,4,5], [5,2,10]);=> [1,3,4]if(_.difference(arr1, arr2).length==0&&_.difference(arr2, arr1).length==0) {? //兩個(gè)數(shù)組相同, 數(shù)組元素有obj之類的不知行不行}
連接兩個(gè)數(shù)組苞氮,用hash判斷重復(fù)
https://github.com/hanzichi/u...?不知道有沒有幫助
來源https://segmentfault.com/q/1010000006845104?_ea=1150060