1

I have the following array:

$scope.myData = [
                 {id: 1, age: 50},
                 {id: 2, age: 43},
                 {id: 8, age: 27},
                 {id: 9, age: 29}
                ];

What I would like to do is to remove a row if given the row id value. I understand that I could use something like:

$scope.myData.splice(0,1);

But how can I determine the row number if for example I am given:

var idToRemove = 8;

Here is a solution I was given that uses jQuery. Unfortunately I don't use jQuery so I am looking for a javascript solution.

    function remove(array, property, value) {
        $.each(array, function(index, result) {
            if (result[property] == value) {
                array.splice(index, 1);
            }
        });    
    };

2 Answers 2

3

Here's a way that works, with looping backwards (in case the same property you're targeting matches more than once):

function remove(array, property, value) {
    var i, j, cur;
    for (i = array.length - 1; i >= 0; i--) {
        cur = array[i];
        if (cur[property] === value) {
            array.splice(i, 1);
        }
    }
}

DEMO: http://jsfiddle.net/RbfTt/2/

And here's the same thing with a while loop:

function remove(array, property, value) {
    var i = array.length,
        j, cur;
    while (i--) {
        cur = array[i];
        if (cur[property] === value) {
            array.splice(i, 1);
        }
    }
}

DEMO: http://jsfiddle.net/RbfTt/3/

Looping backwards is required when it's possible for more than one item to match, because .splice() will change the array in place and mess up the looping.

If multiple items shouldn't match, then a normal incrementing for loop will work, but you might want to put in a break; to make sure it doesn't continue looping.

Sign up to request clarification or add additional context in comments.

Comments

0

My version..

function remove(property, num, arr) {
    for (var i in arr) {
        if (arr[i][property] == num)
            arr.splice(i, 1);
    }
}

Usage:

remove('id', 8, myData);

3 Comments

Why are you using a for in loop with an array?
@AlexCheuk Well, you shouldn't, unless you do it right. It will loop over the length and any other properties, including custom prototype ones.
@AlexCheuk: There are lots of things you "can" do in JavaScript. Doesn't mean they're good.

Your Answer

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