1

How can I remove an object from an Array by id for example:

users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]

Say I want to remove user with id "10051" using javascript, I tried searching the internet but couldn't find anything?

plus I do not want to use underscore!

unknown
  • 846
  • 3
  • 15
  • 38
  • 1
    You're getting answers showing how to build a new, filtered Array, but your question seems to ask how to remove it from the current Array. Which one did you need? – Pokey Apr 22 '13 at 00:42

4 Answers4

4

plus I do not want to use underscore!

The native method for this is .filter():

var removeId = "4567";
users = users.filter(function (user) { return user.id !== removeId; });

Note that it requires the engine be ES5-compatible (or a polyfill).

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
2
for (var i = 0; i < users.length; ++i)
{
    if ( users[i].id == "10051" )
    {
        users[i].splice(i--, 1);
    }
}
David G
  • 94,763
  • 41
  • 167
  • 253
2

You could use .filter method of array.

users = users.filter(function(el) {return el.id !== '10051'});
xdazz
  • 158,678
  • 38
  • 247
  • 274
1
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}];

/* users.length= 2 */

function removebyProperty(prop, val, multiple){
    for(var i= 0, L= this.length;i<L;i++){
        if(i in this && this[i][prop]=== val){
            this.splice(i, 1);
            if(!multiple) i= L;
        }
    }
    return this.length;
}

removebyProperty.call(users,'id',"10051");

returned value: (Number) 1

kennebec
  • 102,654
  • 32
  • 106
  • 127
  • I'd be curious to know why you used `this` in the function along with `.call()` instead of just receiving the Array as a parameter, eliminating the need for `.call()`. – Pokey Apr 22 '13 at 00:51
  • @Pokey- well, it is a narrowly focused function that does one thing on one particular sort of object. I'm comfortable using it as a method of the object, so I call it like one. – kennebec Apr 22 '13 at 05:04