0

I have an array of objects and I am removing elements based on object value, without knowing which element it is.

So... those lovely people who flagged my question as duplicate and suggest I read How do I remove a particular element from an array in JavaScript? are not helping.

My question... again...

I have an array of objects

  • I want to search and remove specific elements from the array. I have a solution that is long winded (loop thru the array once, make a list of element id's, then slice one by one in another loop). I am hoping there is another method (enhance my skillset too).

    myarray.filter(function(item)
    {
        if( item.flag==="Y" )
        {
            // how to delete element from myarray
            // delete implies remove it from myarray
        }
    });
    

All help appreciated =)

Community
  • 1
  • 1

2 Answers2

1

You have at least two options:

Create a new array with filter

The first is to create a new array containing only the entries you want. You're already on the right track with filter:

myArray = myArray.filter(function(item) {
    return item.flag !== "Y";
});

The new array will only have the entries that the callback returned a truthy value for. In this case, only ones whose flag is !== "Y". Entries whose flag is === "Y" will be left out of it.

Note that if you have other references to this same array in other variables, they will continue to point to the old array. Only myArray (in the above) gets a reference to the new array.

Modify the existing array with splice and a loop

The second is to use a while loop and splice:

var n = 0;
while (n < myArray.length) {
    if (myArray[n].flag === "Y") {
        // Remove it
        myArray.splice(n, 1);
    } else {
        // Move to next
        ++n;
    }
}

Note we don't move to next if we remove one, because we need to test the one after it (which is now at the previous index).

Or as Nina points out in a comment, a for loop going backward:

for (var n = myArray.length - 1; n >= 0; --n) {
    if (myArray[n].flag === "Y") {
        // Remove it
        myArray.splice(n, 1);
    }
}

In that case, since we're modifying the array (not creating a new one), the changes will be visible through any reference to that same array, not just myArray. (Since they all point to the same object, which we modified the state of.)

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
0

Remove object in array by its property-value:

Remove value: 30:

arr.splice(arr.map(el => el.value).indexOf(30), 1);

DEMO

Remove name: "John":

arr.splice(arr.map(el => el.name).indexOf("John"), 1);
John
  • 734
  • 5
  • 12