Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove an element in a list, using forEach?

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.

like image 685
TIMEX Avatar asked Aug 05 '11 00:08

TIMEX


People also ask

How do I remove an item from a foreach?

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.

Can I remove item from List in foreach C#?

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.

Can we remove an element by using foreach loop?

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.

How do I remove an object from an array in foreach?

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); } });


1 Answers

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.

like image 75
Gajus Avatar answered Sep 19 '22 21:09

Gajus