我想知道,以下列方式比较两个数组的最有效方法是什么:
有什么想法吗?
答案 0 :(得分:0)
通常最有效的方式是本机方式,所以这样的事情应该表现得很好:
console.clear();
var one = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var two = ['a', 'b', 'c', 'e', 'g'];
function insertMissing(insertTo, insertFrom) {
insertFrom.filter(function (from) {
return insertTo.some(function (too) {
return too === from
}) == false;
}).forEach(function (el) {
insertTo.push(el);
})
}
insertMissing(two, one);
console.log(one, two);
我需要知道确切的对象标记才能知道要匹配什么,但这证明了基础知识。
下面是一个用对象演示它的片段:
console.clear();
var one = [{
'id' : 'a'
}, {
'id' : 'b'
}, {
'id' : 'c'
}, {
'id' : 'd'
}, {
'id' : 'e'
}, {
'id' : 'f'
}, {
'id' : 'g'
}
];
var two = [{
'id' : 'a'
}, {
'id' : 'b'
}, {
'id' : 'c'
}, {
'id' : 'e'
}, {
'id' : 'g'
}
];
function insertMissing(insertTo, insertFrom) {
insertFrom.filter(function (from) {
return insertTo.some(function (too) {
return too.id === from.id
}) == false;
}).forEach(function (el) {
insertTo.push(el);
})
}
insertMissing(two, one);
console.log(one);
console.log(two);
最后,一个覆盖对象属性的版本:
console.clear();
var one=[{'id':'a','value':1},{'id':'b','value':1},{'id':'c','value':1},{'id':'d','value':1},{'id':'e','value':3},{'id':'f','value':1},{'id':'g','value':1}];
var two=[{'id':'a','value':1},{'id':'b','value':1},{'id':'c','value':1},{'id':'e','value':1},{'id':'g','value':1}];
function insertMissing(insertTo, insertFrom) {
//Validate existing elements
insertTo.forEach(function (too) {
var from;
insertFrom.forEach(function (f, index) {
if (f.id == too.id && typeof from == 'undefined') {
from = index;
}
});
if (typeof from == "number") {
for (var i in insertFrom[from]) {
if (insertFrom[from].hasOwnProperty(i)) {
if (insertFrom[from][i] !== too[i]) {
too[i] = insertFrom[from][i];
}
}
}
}
});
//Insert missing elements
insertFrom.filter(function (from) {
return insertTo.some(function (too) {
return too.id === from.id
}) == false;
}).forEach(function (el) {
insertTo.push(el);
})
}
insertMissing(two, one);
console.log(one);
console.log(two);