var people = ['alex','jason','matt']; people.forEach(function(p){ if(p.length > 4){ //REMOVE THIS PERSON or pop it out of the list or whatever } }); console.log(people) //should return ['alex','matt']
I want to remove an element out of the list, using this forEach loop.
Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.
You can't use . Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute.
It is not recommended adding or removing elements from a list within a loop as an index of its elements, and the length of the list is changed. This might lead to the incorrect output, or java. util.
To remove element from array in forEach loop with JavaScript, we can use the array splice method. const review = ["a", "b", "c", "b", "a"]; review. forEach((item, index, arr) => { if (item === "a") { arr. splice(index, 1); } });
Use the right tools for the right job. In this case:
for (var i = 0; i < data.length; i++) { if (data[i].value === 5) { data.splice(i--, 1); } }
or as @nnnnnn has suggested, loop backwards:
for (var i = data.length-1; i >= 0; i--) { if (data[i].value === 5) { data.splice(i, 1); } }
However, you should consider using Array.prototype.filter()
:
data = data.filter(function (e) { return e.value !== 5; });
or a utility function library such as lodash or underscore, which provide a function for removing elements from an array:
_.remove(data, function (e) { return e.value === 5; });
The benefit of the latter two is that your code becomes more readable.
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