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
0
: 172 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

1
At:- 8/25/2021 4:23:16 PM
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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly