How do I remove a particular element from an array in JavaScript?

I have an array of integers, and I'm using the .push() method to add elements to it.

Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);
.

I have to use core JavaScript - no frameworks are allowed.

Text Copied From stackoverflow.com
on : Sat, Apr 23, 2011 Views : 4308950

Accepted Answer

First, find the index of the element you want to remove:

var array = [2, 5, 9];
 var index = array.indexOf(5);
 

Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.

Then remove it with splice:

if (index > -1) 
{

  array.splice(index, 1);
 

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


If you need indexOf in an unsupported browser, try the following polyfill. Find more info about this polyfill here.

Array.prototype.indexOf || (Array.prototype.indexOf = 
function(d, e) 
{

  var a;

  if (null == this) throw new TypeError('this is null or not defined');

  var c = Object(this),
 
  b = c.length >>> 0;

  if (0 === b) return -1;

  a = +e || 0;

  Infinity === Math.abs(a) &
&
 (a = 0);

  if (a >= b) return -1;

  for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0);
 a < b;

{

 
  if (a in c &
&
 c[a] === d) return a;

 
  a++
  
}
  return -1 
});
 
Text Copied From stackoverflow.com
on : Sat, Apr 23, 2011

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp