Possibly a very obvious question from a beginner:
If I have the following array...
var arr =
[
{id: 1, item: "something", description: "something something"},
{id: 2, item: "something else", description: "something different"},
{id: 3, item: "something more", description: "more than something"}
]
... and wanted to delete a specific object within it by calling on the id (in this case by clicking on an div given the corresponding id)...
var thisItem = $(this).attr("id");
... could I do this without using a for loop to match arr[i] and thisItem? And if so, how? I'm going to have a big array so running a for-loop seems very heavy handed.
Thanks!
You can use Array.filter for filtering any array. This method takes a filtering function as its argument and runs it on every element of the original array. If the return value of this function is false, that element is filtered out of the new array that is returned. Original array is not affected.
var arr =
[
{id: 1, item: "something", description: "something something"},
{id: 2, item: "something else", description: "something different"},
{id: 3, item: "something more", description: "more than something"}
];
function filterArray( id ){
return arr.filter(function(item){
return item.id != id;
});//filter
}//filterArray()
console.log( filterArray(2) );
You can use JQuery's grep
arr = jQuery.grep(arr, function(value) {
return value.id != id;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With