[英]Javascript array check and combine
I have two arrays containing some objects and I need to know how to combine them and exclude any duplicates. 我有两个包含一些对象的数组,我需要知道如何组合它们并排除任何重复项。 (For example, the object that contains
apple: 222
from the second array should be excluded, if it already exists in the first array.) (例如,如果第一个数组中已存在包含第二个数组中的
apple: 222
的对象,则应将其排除在外。)
Check below: 检查如下:
var arr1 = [
{apple: 111, tomato: 55},
{apple: 222, tomato: 55}
]
var arr2 = [
{apple: 222, tomato: 55},
{apple: 333, tomato: 55}
]
I want the result to be like this: 我希望结果是这样的:
var res = [
{apple: 111, tomato: 55},
{apple: 222, tomato: 55},
{apple: 333, tomato: 55}
]
How can I do that in javascript? 我怎么能用javascript做到这一点?
You could write a dedupe function. 你可以写一个重复数据删除函数。
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');
Does this solution fit with your needs ( demo ) ? 这个解决方案是否符合您的需求( 演示 )?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.