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!

1

3 Answers 3

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) );
Sign up to request clarification or add additional context in comments.

2 Comments

array.filter is the way to go
Works great. Thank you!
2

You can use JQuery's grep

arr = jQuery.grep(arr, function(value) {
  return value.id != id;
});

1 Comment

This also works perfectly. Thanks!
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;
  });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.