1

I have an array

var arr = [{"id":"1","name":"One"},{"id":"2","name":"Two"}]

I push to the array

arr.push(X)

But how can I remove for example {"id":"1","name":"One"} from this array by name?

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Rafff
  • 1,510
  • 3
  • 19
  • 38
  • possible duplicate of [remove objects from array by object property](http://stackoverflow.com/questions/16491758/remove-objects-from-array-by-object-property) – Felix Kling May 06 '14 at 23:40

2 Answers2

5

In plain javascript, you have to search through the array looking for a name match in each object and then remove that object:

function removeFromArrayByName(arr, name) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].name === name) {
             arr.splice(i, 1);
             return;
        }
    } 
}

Or if there might be more than one match and you want to remove all the matches there are, you can do this (does a backward traversal and doesn't return when it finds a match):

function removeFromArrayByName(arr, name) {
    for (var i = arr.length - 1; i >= 0; i--) {
        if (arr[i].name === name) {
             arr.splice(i, 1);
        }
    } 
}

Or, you could even make it more generic where you pass in the property name to search too:

function removeFromArrayByName(arr, prop, val) {
    for (var i = arr.length - 1; i >= 0; i--) {
        if (arr[i][prop] === val) {
             arr.splice(i, 1);
        }
    } 
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

The question is for plain js but if you use jquery, you can write a function like this:

function removeByName(arr, key){
   return $.grep(arr, function (n,i) {
      return n.name != key;
   });
}

In your case, I will call removeByName(arr,'One');