0

I am aware that you can remove and element from javascript array in various ways like using Array.splice(), pop(), etc. or by its value. Now I wonder, is it possible using vanilla js to remove an element of a javascript array by reference like you do in other programming language like c#?

example:

    var item = items.find(function(item) { return item.acreg === "abc-123";});
    //do some other things with item
    items.remove(item);
  • 1
    Related: http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript You may find the index of element by reference using .indexOf() method – Peeyush Kushwaha May 18 '16 at 06:58
  • There should be a VanillaJS tag in SO :D – Gogol May 18 '16 at 07:11

1 Answers1

4

Yes you can.

Use indexOf with Array.splice:

var fruits = ["banana", "apple", "watermelon"];

// Remove "apple" only if indexOf found a matching element in the array
if ( fruits.indexOf("apple") > -1 ) {
    fruits.splice( fruits.indexOf("apple") , 1 )
}

This is overly simplified, but should get you in the right direction.

elad.chen
  • 2,182
  • 5
  • 22
  • 32