Remove element from an array in JavaScript using different ways



JavaScript array has a variety of ways you can remove element from array.

1) Using splice() function

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
  1. var arrayList = [1, 2, 3];
  2. var index = arrayList.indexOf(2);
  3. if (index > -1) {
  4. arrayList.splice(index, 1);
  5. }
  6. console.log(arrayList);
  7. // Output = [2, 9]

2) Using pop() method

The pop method removes the last element of the array, returns that element, and updates the length property.
  1. var arrayList = [1, 2, 3];
  2. arrayList.pop();
  3. console.log( arrayList );
  4. // Output = [1, 2]

3) Using shift() method

The shift method removes the first element of the array, returns that element, and updates the length property.
  1. var arrayList = ['1', '2', '3'];
  2. arrayList.shift();
  3. console.log( arrayList );
  4. // Output = ['2', '3']

4) Using filter() method

The filter() has a single parameter, a callback method.
  1. var arrayList = [1, 2, 3, 4, 5];
  2. var filtered = arrayList.filter(function(value, index) {
  3. return value > 3;
  4. });
  5. console.log( filtered );
  6. // Output => [4, 5]

5) Using the Delete Operator

You can remove specific array elements using the delete operator:
  1. var arrayList = [1, 2, 3, 4, 5, 6];
  2. delete arrayList[4]; // delete element with index 4
  3. console.log( arrayList );
  4. // [1, 2, 3, 4, undefined, 6]
There are different methods and techniques you can use to purge unwanted array items. You can suggest more methods in the below comment box.

Post a Comment

0 Comments