235

I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects.

Data:

[
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

I'm able to search the array using jQuery $grep;

var id = 88;

var result = $.grep(data, function(e){
     return e.id == id;
});

But how can I delete the entire object when id == 88, and return data like the following?

Data:

[
    {"id":"99", "name":"Have fun boys and girls"},
    {"id":"108", "name":"You are awesome!"}
]
5
  • What about using slice function and a little for loop? Commented Feb 9, 2014 at 13:57
  • 1
    Sure, but, reason I wrote this question, is because I am stuck ;) any snippets? Commented Feb 9, 2014 at 13:58
  • Check this post stackoverflow.com/questions/10827894/… Commented Feb 9, 2014 at 14:01
  • The title and question text seem to conflict... suggesting two entirely different approaches: A. remove items from an array versus B. create a new, filtered array. Commented Dec 20, 2016 at 19:54
  • Does this answer your question? Remove array element based on object property Commented May 16, 2022 at 14:47

15 Answers 15

308

Here is a solution if you are not using jQuery:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});
Sign up to request clarification or add additional context in comments.

6 Comments

Is this better than doing findIndex() and then splice(index, 1) on parent array?
You can reduce this to a single line by using: myArr = myArray.filter(obj => obj.id !== id);
even more concise arr = arr.filter( obj => obj.id !== id);
Can someone explain about time complexity difference between ' filter() ' and ' findIndex()+splice(index,1) '
@NamanDutta Both filter and indexOf()+splice() are O(N)
|
172

I can grep the array for the id, but how can I delete the entire object where id == 88

Simply filter by the opposite predicate:

var data = $.grep(data, function(e){ 
     return e.id != id; 
});

10 Comments

This answer provides the most concise and idiomatic solution for jQuery
In you case where you want to delete all items with id=something is fine ... but be careful when using $.grep as it searches the full array and for long arrays it is not efficient. Sometimes you just need to check if the element exists inside the array by a given ID, then is better to use another iteration method ;)
This doesn't remove that object from list
@ArunSivan slice doesn't remove anything either. Not sure what you're getting at. If you have a specific problem yourself, you might want to ask a new question.
@Learner data.filter(e => !ids.includes(e.id))
|
109

You can simplify this, and there isn't really any need for using jQuery here.

var id = 88;

for(var i = 0; i < data.length; i++) {
    if(data[i].id == id) {
        data.splice(i, 1);
        break;
    }
}

Just iterate through the list, find the matching id, splice, and then break to exit your loop.

3 Comments

+1, but you should mention that this does delete only the first item which matches.
... And if you need to delete each matched items, loop on reverse order with i=data.length; i > 0; i-- and don't use break.
i = data.length will break any data[i], it should be something like i=data.length -1 ; i > -1; i--
45

There's a new method to do this in ES6/2015 using findIndex and the array spread operator:

const index = data.findIndex(obj => obj.id === id);
const newData = [
    ...data.slice(0, index),
    ...data.slice(index + 1)
]

You can turn it into a function for later reuse like this:

function remove(array, key, value) {
    const index = array.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...array.slice(0, index),
        ...array.slice(index + 1)
    ] : array;
}

This way, you can remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):

const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");

Or you can put it on your Array.prototype:

Array.prototype.remove = function (key, value) {
    const index = this.findIndex(obj => obj[key] === value);
    return index >= 0 ? [
        ...this.slice(0, index),
        ...this.slice(index + 1)
    ] : this;
};

And use it this way:

const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");

2 Comments

findIndex() is really great! 👍
What if you have more than one key and value?
17

Native ES6 solution:

const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
    data.splice(pos, 1);

If you know that the element is in the array for sure:

data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);

Prototype:

Array.prototype.removeByProp = function(prop,val) {
    const pos = this.findIndex(x => x[prop] === val);
    if (pos >= 0)
        return this.splice(pos, 1);
};

// usage:
ar.removeByProp('id', ID_TO_REMOVE);

http://jsfiddle.net/oriadam/72kgprw5/

Note: this removes the item in-place. If you need a new array, use filter as mentioned in previous answers.

2 Comments

You do not handle the case where the id is not found. In this case, your solution remove the element of the array
these is very clean
12
var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

If you are using jQuery, use jQuery.grep like this:

items = $.grep(items, function(item) { 
  return item.id !== '88';
});
// items => [{ id: "99" }, { id: "108" }]

Using ES5 Array.prototype.filter:

items = items.filter(function(item) { 
  return item.id !== '88'; 
});
// items => [{ id: "99" }, { id: "108" }]

2 Comments

Noooooo! Do not use jQuery map as a filter.
Agree! Your solution with grep is the right solution with jQuery.
9

Assuming that ids are unique and you'll only have to remove the one element splice should do the trick:

var data = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
],
id = 88;

console.table(data);

$.each(data, function(i, el){
  if (this.id == id){
    data.splice(i, 1);
  }
});

console.table(data);

2 Comments

You have the elements in your callback function backwards. It should be each(data,function(idx,ele). I'll bill you later for the 30 min I wasted figuring that out :)
Oops. The least I can do in that case is update my answer. I feel really bad about your wasted 30 minutes of life.
6
const data = [
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
];

Here we get the index of the object whose value of the id is "88"

const index = data.findIndex(item => item.id === "88");
console.log(index); // 0

We use splice function to remove the specified object from data array

data.splice(index,1);
console.log(data); // [{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}]

Comments

6

I agree with the previous answers. A simple way if you want to find an object by id and remove it is simply like the below code:

var obj = JSON.parse(data);
var newObj = obj.filter(item => item.Id != 88);

Comments

4

Maybe you are looking for $.grep() function:

arr = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

id = 88;
arr = $.grep(arr, function(data, index) {
   return data.id != id
});

Comments

3
Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle

Comments

3

sift is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in Node.js.

var collection = [
    {"id":"88",  "name":"Lets go testing"},
    {"id":"99",  "name":"Have fun boys and girls"},
    {"id":"108", "name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);

It supports filters like $in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type, and $regex, and strives to be API-compatible with MongoDB collection filtering.

1 Comment

Why no upwotes? If this thing is properly writen and have no terrible bugs it should beextremely usefull.
0

Make sure you coerce the object id to an integer if you test for strict equality:

var result = $.grep(data, function(e, i) { 
  return +e.id !== id;
});

Demo

Comments

0

If you are using Underscore.js, it is easy to remove an object based on a key.

Example:

  var temp1=[{id:1,name:"safeer"},  // Temporary array
             {id:2,name:"jon"},
             {id:3,name:"James"},
             {id:4,name:"deepak"},
             {id:5,name:"ajmal"}];

  var id = _.pluck(temp1,'id'); // Get id array from temp1
  var ids=[2,5,10];             // ids to be removed
  var bool_ids=[];
  _.each(ids,function(val){
     bool_ids[val]=true;
  });
  _.filter(temp1,function(val){
     return !bool_ids[val.id];
  });

Comments

0

Some shortly:

arr = arr.filter(o => o.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.