Reputation: 147
I have one array of object from which i have to remove selected object and create new array of object.
//Get all items from 'Product' dropdown
var allItems = [{ text: "India", value: "10" }, { text: "Canada", value: "12" }, { text: "US", value: "17" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" }];
var itemsToRemove = ["17", "10"];
var newItems = [{ text: "Canada", value: "12" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" }];
Upvotes: 1
Views: 3175
Reputation: 147
Thanks everybody for you answers, this is how i solved it.
var newItems = allItems.filter(function(item) {
for (var i = 0; i < itemsToRemove.length; i++)
if (itemsToRemove[i] == item.value) return false;
return true;
});
Upvotes: 0
Reputation: 1465
Try It.
var allItems = [{
text: "India",
value: "10"
}, {
text: "Canada",
value: "12"
}, {
text: "US",
value: "17"
}, {
text: "Austria",
value: "18"
}, {
text: "South Africa",
value: "14"
}];
var itemsToRemove = ["17", "10"];
for (var i = 0; i < allItems.length; i++) {
if(itemsToRemove.indexOf(allItems[i].value) >= 0) {
allItems.splice(i, 1);
}
}
Upvotes: 0
Reputation: 189
You can simply use splice for properly deleting and indexing javascript array.
var allItems = [{
text: "India",
value: "10"
}, {
text: "Canada",
value: "12"
}, {
text: "US",
value: "17"
}, {
text: "Austria",
value: "18"
}, {
text: "South Africa",
value: "14"
}];
var itemsToRemove = ["17", "10"];
for (var i = 0; i < allItems.length; i++) {
for (var j = 0; j < itemsToRemove.length; j++) {
if (allItems[i].value == itemsToRemove[j])
allItems.splice(i, 1);
}
}
Upvotes: 2
Reputation: 145408
var newItems = allItems.filter(function(e) {
// A.indexOf(x) == -1 if x is not found in A
return itemsToRemove.indexOf(e.value) === -1;
});
var allItems = [
{ text: "India", value: "10" },
{ text: "Canada", value: "12" },
{ text: "US", value: "17" },
{ text: "Austria", value: "18" },
{ text: "South Africa", value: "14" }
];
var itemsToRemove = ["17", "10"];
var newItems = allItems.filter(function(e) {
return itemsToRemove.indexOf(e.value) === -1;
});
console.log( newItems );
Upvotes: 2