Is it possible to remove something from an array using foreach?
var array = [1,2,3,4,5,6,7,8];
array.forEach(function(data){
if (data == 4) {
// do something here
}
});
console.log(array);
Is it possible to remove something from an array using foreach?
var array = [1,2,3,4,5,6,7,8];
array.forEach(function(data){
if (data == 4) {
// do something here
}
});
console.log(array);
I would advise against using the forEach function. It affects the iterator and skips the next item. Better: use a reverse for loop and remove the item by index.
var array = [1,2,3,4,5,6,7,8];
for (var i = array.length - 1; i > -1; i--) {
if (array[i] == 4) {
array.splice(i, 1);
}
}
Fiddle: https://jsfiddle.net/uu94y8Lx/
Try like this:
array.forEach(function(data){
if (data == 4){
console.log('done')
array.splice(data, 1);
}
});
Also as commented by mario its not recommended to modify the array you're looping on, so you can do like this:
var array1 = [];
array.forEach(function(data){
if(array.length === 4){
array1.push(data);
}
});
Also you can use the for loop like this:
var array = [1,2,3,4,5,6,7,8],i;
for (i = 0; i < array.length; ++i) {
if (array[i] === 4) {
array.splice(i--, 1);
}
}
console.log(array);
I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it is possible to remove an item with array.splice(data, 1)
.