如果值不存在,则将一个数组对象推入另一个数组对象 [英] push a array object into another array object if the value not exists

查看:43
本文介绍了如果值不存在,则将一个数组对象推入另一个数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果值不存在,则需要将数组对象(arr1)的值推入另一个数组对象(arr2).现有值不会推入另一个数组.

Need to push the array object(arr1) valeus into another array object(arr2) if the value not exist. The existing values will not push into another array.

var arr1 = [{
    name: 'fred'
}, {
    name: 'bill'
}, {
    name: 'ted'
}, {
    name: 'james'
}];

var arr2 = [{
    name: 'spil'
}, {
    name: 'fred'
}, {
    name: 'bill'
},{
    name: 'paul'
}, {
    name: 'stone'
}];

function add(name) {
    var found = arr1.some(function (el) {
      return el.name === name;
    });
    if (!found) {
        arr1.push(arr2);
    }
    return arr2;
}

小提琴

推荐答案

如果name属性已经在 arr1 中,则可以使用哈希表进行查找.如果没有,则将实际项目推送到 arr1 .

You could use a hash table for look up, if the name property is already in arr1. If not push the actual item to arr1.

var arr1 = [{ name: 'fred' }, { name: 'bill' }, { name: 'ted' }, { name: 'james' }],
    arr2 = [{ name: 'toString' }, { name: 'spil' }, { name: 'fred' }, { name: 'bill' }, { name: 'paul' }, { name: 'stone' }],
    hash = Object.create(null);

arr1.forEach(function (a) {
    hash[a.name] = true;
});
arr2.forEach(function (a) {
    hash[a.name] || arr1.push(a);
});

console.log(arr1);

PS

只需说明一下,为什么将 Object.create(null)(一个真正空的对象)作为哈希,而不将 {} (一个空对象)作为哈希.请注意项目 {名称:'toString'} .在第一个部分中,插入该项目,而在第二个部分中,则不插入该项目,因为 hash 具有名称为 toString 的属性.

Just to make clear, why Object.create(null), a really empty object as hash and not {}, an empty object. Pay attention to the item { name: 'toString' }. In the firt part, the item gets inserted, in the second not, because hash has a property with the name toString.

var arr1 = [{ name: 'fred' }, { name: 'bill' }, { name: 'ted' }, { name: 'james' }],
    arr2 = [{ name: 'toString' }, { name: 'spil' }, { name: 'fred' }, { name: 'bill' }, { name: 'paul' }, { name: 'stone' }],
    hash = {}; // now an object

arr1.forEach(function (a) {
    hash[a.name] = true;
});
arr2.forEach(function (a) {
    hash[a.name] || arr1.push(a);
});

console.log(arr1);

这篇关于如果值不存在,则将一个数组对象推入另一个数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆