If I have array, for example:
a = ["a", "b", "c"]
I need something like
a.remove("a");
How can I do this?
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.
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.
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.
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");
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 }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With