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?

1

2 Answers 2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.