Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an object from an array using one value [duplicate]

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!

like image 835
dedaumiersmith Avatar asked Apr 29 '26 18:04

dedaumiersmith


2 Answers

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) );
like image 163
Mohit Bhardwaj Avatar answered May 02 '26 09:05

Mohit Bhardwaj


You can use JQuery's grep

arr = jQuery.grep(arr, function(value) {
  return value.id != id;
});
like image 38
MrFabio Avatar answered May 02 '26 09:05

MrFabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!