3

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!

Prashant Ghimire
  • 4,890
  • 3
  • 35
  • 46
dedaumiersmith
  • 337
  • 4
  • 14
  • For latest browsers [`arr.splice(arr.findIndex(o => o.id === 2), 1);`](https://jsfiddle.net/54mLn6m3/) – Tushar Jul 05 '16 at 13:57

3 Answers3

4

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) );
Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64
2

You can use JQuery's grep

arr = jQuery.grep(arr, function(value) {
  return value.id != id;
});
MrFabio
  • 586
  • 2
  • 15
  • 31
0

Plain JS Solution:

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"
}];

var filtered = filterArrayByElemId(arr, 2);
console.log(filtered);

function filterArrayByElemId(arr, id) {
  return arr.filter(function(item) {
    return item.id != id;
  });
}
Prashant Ghimire
  • 4,890
  • 3
  • 35
  • 46