Javascript数组检查和组合
我有两个数组,其中包含一些对象,我需要知道如何组合它们并排除任何重复项。(例如,如果第一个数组中已经存在包含第二个数组中的Javascript数组检查和组合,javascript,Javascript,我有两个数组,其中包含一些对象,我需要知道如何组合它们并排除任何重复项。(例如,如果第一个数组中已经存在包含第二个数组中的apple:222的对象,则应将其排除在外。) 检查以下内容: var arr1 = [ {apple: 111, tomato: 55}, {apple: 222, tomato: 55} ] var arr2 = [ {apple: 222, tomato: 55}, {apple: 333, tomato: 55} ] 我希望结果是这
apple:222
的对象,则应将其排除在外。)
检查以下内容:
var arr1 = [
{apple: 111, tomato: 55},
{apple: 222, tomato: 55}
]
var arr2 = [
{apple: 222, tomato: 55},
{apple: 333, tomato: 55}
]
我希望结果是这样的:
var res = [
{apple: 111, tomato: 55},
{apple: 222, tomato: 55},
{apple: 333, tomato: 55}
]
如何在javascript中做到这一点?您可以编写一个重复数据消除函数
if (!Array.prototype.dedupe) {
Array.prototype.dedupe = function (type) {
for (var i = 0, l = this.length - 1; i < l; i++) {
if (this[i][type] === this[i + 1][type]) {
this.splice(i, 1);
i--; l--;
}
}
return this;
}
}
function combine(arr1, arr2, key) {
return arr1
.concat(arr2)
.sort(function (a, b) { return a[key] - b[key]; })
.dedupe(key);
}
var combined = combine(arr1, arr2, 'apple');
if(!Array.prototype.deduplicate){
Array.prototype.dedupe=函数(类型){
for(var i=0,l=this.length-1;i
.此解决方案是否符合您的需要()
这些“内部数组”是javascript对象,FWIW。请发布数组文字(而不是PHP)您的数组以“(”开头,以“}”结尾?查找数组的concat方法。不确定您为什么更改示例代码,但我已经修改了我的答案。
var res, i, item, prev;
// merges arrays together
res = [].concat(arr1, arr2);
// sorts the resulting array based on the apple property
res.sort(function (a, b) {
return a.apple - b.apple;
});
for (i = res.length - 1; i >= 0; i--) {
item = res[i];
// compares each item with the previous one based on the apple property
if (prev && item.apple === prev.apple) {
// removes item if properties match
res.splice(i, 1);
}
prev = item;
}