Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a specific element in array in JavaScript [duplicate]

If I have array, for example:

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

I need something like

a.remove("a"); 

How can I do this?

like image 902
Adham Avatar asked Jun 07 '12 22:06

Adham


People also ask

How do I remove a repeated value from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you duplicate an array in JavaScript?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

Can array have duplicate values JavaScript?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.


2 Answers

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"); 
like image 110
Danilo Valente Avatar answered Sep 21 '22 02:09

Danilo Valente


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 }); } 
like image 38
georg Avatar answered Sep 22 '22 02:09

georg