How to remove element from array in forEach loop?

Q & ACategory: AllHow to remove element from array in forEach loop?
Luci Staff asked 3 years ago

Iterate and mutate an array using Array.prototype.splice

var pre = document.getElementById(‘out’);
function log(result) {
pre.appendChild(document.createTextNode(result + ‘\n’));
}
var review = [‘a’, ‘b’, ‘c’, ‘b’, ‘a’];
review.forEach(function(item, index, object) {
if (item === ‘a’) {
object.splice(index, 1);
}
});
log(review);
<pre id="out"></pre>

1 Answers
Luci Staff answered 3 years ago
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);