I'm trying to edit an array and remove elements that do not meet a certain condition. If I use a reverse for loop
combined with .splice(index,n)
, the code works just fine. I'm stuck at implementing the same using the ES6 for...of
loop
let array=[1,2,3];
//reverse for loop
for(var i=array.length - 1; i>=0; i--) {
if(array[i]>=2) {
/*Collect element before deleting it.*/
array.splice(i,1);
}
}
console.log(array);
// returns [1]
Using for..of
let array=[1,2,3];
for(let entry of array) {
if(entry>=2) {
let index = array.indexOf(entry);
/*The array is being re-indexed when I apply
.splice() - the loop will skip over an index
when one element of array is removed*/
array.splice(index, 1);
}
}
console.log(array);
//returns [1,3]
Is there a way to achieve this functionality using a for...of
loop or do I have to stick to the reverse for loop
Update
I need to collect the entries that don't meet the elements removed by either the filter()
or reverse for loop
functions to a secondary array.
.filter
instead, much easier – Volnywhile
like this – Peavy