33

If I have array, for example:

a = ["a", "b", "c"] 

I need something like

a.remove("a"); 

How can I do this?

2
  • Settle Down. I'm coming up with a duplicate for you since you clearly didn't search for yourself.
    – user1106925
    CommentedJun 7, 2012 at 22:20
  • arr.splice(arr.indexOf(elm),1) will remove an element 'elm' from array 'arr'CommentedAug 21, 2018 at 19:34

6 Answers 6

16
var newArray = []; var a=["a","b","c"]; for(var i=0;i<a.length;i++) if(a[i]!=="a") newArray.push(a[i]); 

As of newer versions of JavaScript:

var a = ["a","b","c"]; var newArray = a.filter(e => e !== "a"); 
4
  • 2
    You know there is .splice right?CommentedJun 7, 2012 at 22:19
  • 2
    Yes, I know. But I'm considering that the array can have more than one "a"CommentedJun 7, 2012 at 22:21
  • I didn't think of that. Good point. +1CommentedJun 7, 2012 at 22:22
  • The array has only unique values !
    – Adham
    CommentedJun 7, 2012 at 22:27
7
remove = function(ary, elem) { var i = ary.indexOf(elem); if (i >= 0) ary.splice(i, 1); return ary; } 

provided your target browser suppports array.indexOf, otherwise use the fallback code on that page.

If you need to remove all equal elements, use filter as Rocket suggested:

removeAll = function(ary, elem) { return ary.filter(function(e) { return e != elem }); } 
    3

    If you're using a modern browser, you can use .filter.

    Array.prototype.remove = function(x){ return this.filter(function(v){ return v !== x; }); }; var a = ["a","b","c"]; var b = a.remove('a'); 
    0
      2

      I came up with a simple solution to omit the necessary element from the array:

      <script> function myFunction() { var fruits = ["One", "Two", "Three", "Four"]; <!-- To drop the element "Three"--> <!-- splice(elementid, number_of_element_remove) --> fruits.splice(2, 1); var x = document.getElementById("demo"); x.innerHTML = fruits; } </script> 
      1
      • this is valid for Array and arraylist bothCommentedDec 10, 2013 at 6:01
      1
      let xx = ['a','a','b','c']; // Array let elementToRemove = 'a'; // Element to remove xx =xx.filter((x) => x != elementToRemove) // xx will contain all elements except 'a' 
        0

        If you don't mind the additional payload (around 4 kB minified and gzipped) you could use the without function of the Underscore.js library:

        _.without(["a", "b", "c"], "a"); 

        Underscore.js would give you this function + a lot of very convenient functions.

          Start asking to get answers

          Find the answer to your question by asking.

          Ask question

          Explore related questions

          See similar questions with these tags.