Rafff
Rafff

Reputation: 1518

How to remove array from array using Javascript?

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?

Upvotes: 1

Views: 85

Answers (2)

Tom Luong
Tom Luong

Reputation: 1

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');

Upvotes: 0

jfriend00
jfriend00

Reputation: 708016

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);
        }
    } 
}

Upvotes: 5

Related Questions