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
711k104 gold badges1.1k silver badges1k bronze badges
asked May 6, 2014 at 23:21
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);
 }
 } 
}
answered May 6, 2014 at 23:23
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');

answered May 6, 2014 at 23:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.