当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - push a array object into another array object if the value not exists

问题描述:

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;

}

Fiddle

网友答案:

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);
网友答案:

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat(): var ar1 = [1, 2, 3]; var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);

Will spit out:

"1,2,3"
"4,5,6"
"1,2,3,4,5,6"

The concat does not affect ar1 and ar2 unless reassigned, for example:

ar1 = ar1.concat(ar2);
alert(ar1);

Will display:

"1,2,3,4,5,6"
网友答案:

Use indexOf for get not exist name.Store first your arr1 name as a array !!!

var hasName = arr1.map(function(obj) { return obj.name; });
arr2.filter(function(v,i) { if(hasName.indexOf(v.name) == -1) arr1.push(v); });      
console.log(arr1);
网友答案:

If you have the luxury of using ECMAScript 6 then you can create this lovely block

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

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

arr2.forEach(arr2Item => arr1.find(({ name }) => name === arr2Item.name) || arr1.push(arr2Item));

console.log(arr1);
网友答案:

Hi check this u can push the first array to other array later can use the underscore unique to return only the unique objects

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

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

arr1.push(arr2);
arr1 = _.uniq(arr1, false, function(p) {
    return p.name;
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: