I want to add a new property to each element which are not present in the second array.
That completely changes the question you originally asked.
If the items are mutable, you'd just loop through the array adding the property to selected items. There are many ways to do that, such as forEach
:
arr1.forEach(function(item) {
if (arr2.indexOf(item.name) === -1) {
item.country = "USA";
}
});
Live Example:
var arr1 = [{
"name": "A"
}, {
"name": "B"
}, {
"name": "C"
}, {
"name": "D"
}];
var arr2 = ["C", "D"];
arr1.forEach(function(item) {
if (arr2.indexOf(item.name) === -1) {
item.country = "USA";
}
});
console.log(arr1);
If they're immutable, you'd use map
instead:
arr1 = arr1.map(function(item) {
if (arr2.indexOf(item.name) === -1) {
return /*...create item with `country = "USA"` here...*/;
} else {
return item;
}
});
Live Example:
var arr1 = [{
"name": "A"
}, {
"name": "B"
}, {
"name": "C"
}, {
"name": "D"
}];
var arr2 = ["C", "D"];
arr1 = arr1.map(function(item) {
if (arr2.indexOf(item.name) === -1) {
return {name: item.name, country: "USA"};
} else {
return item;
}
});
console.log(arr1);
Original answer: (to your original question)
You would loop over the resulting array adding the property. There are many ways to do that, such as forEach
:
arr1.forEach(function(item) {
item.country = "USA";
});
Technically, you could make it a side-effect of your filter
, like this:
var arr1 = arr1.filter(function(item){
if (arr2.indexOf(item.name) === -1) {
item.country = "USA";
return true;
};
return false;
});
BUT, side-effects in filter
callbacks (and similar) are generally not a great idea. Unless you know that the resulting array (arr1
) is hundreds of thousands of entries, the second pass keeps things simple by filtering and then modifying.