How to remove element from an array in Javascript?


I am looking an easy and quick way to remove any element from an array in javascript, I can see there is way to add or remove new element in javascript using shift/unshift, but what about when I want to remove element from a specific position in an array? Something like this

arr.RemoveAt(0);

Thanks


Asked by:- bhanu
1
: 1097 At:- 8/25/2021 4:10:58 PM
Javascript arrays







1 Answers
profileImage Answered by:- vikas_jk

First, I will give you answer using plain old Javascript to remove element in an array

To remove an element of an array at location(index) i:

arr.splice(i, 1); //remove 1 item at index 'i' of an array

To Remove every element (numberToremove) of specific type, you need to loop

function removeAllInstancesOfItem(arr, item) {
   for (var i = arr.length; i--;) {
     if (arr[i] === itemToRemove) 
        arr.splice(i, 1);
   }
}

It loops through the array backwards (as indexes and length will change when an item is removed) and removes the item if it's found.

Using JS ES6

let value = 4

let arr = [1, 2, 3, 4, 4, 5]

arr = arr.filter(item => item !== value)

console.log(arr);
// this will print [1,2,3,5]

But as ES6 is not supported in older browser like IE 10 or safari 10 version or below it, you would have to use BabelJS

Custom method to remove by value

You can also create custom method to remove item based on value, we will still use .splice() but it can be helpful

Array.prototype.removeByValue = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === val) {
      this.splice(i, 1);
      i--;
    }
  }
  return this;
}

var cars= ['bmw', 'audi', 'mercedes', 'jaguar'];
cars.removeByValue('audi');

console.log(cars); 
//[bmw', 'mercedes', 'jaguar']

Hope it helps.

1
At:- 8/25/2021 4:23:16 PM Updated at:- 8/11/2022 7:52:27 AM
Thanks for the quick answer. 0
By : bhanu - at :- 8/25/2021 4:24:56 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use