King King - 5 months ago 6
Javascript Question

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

Answer

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);

Comments