I am trying to remove a word from an array based on an index which doesn't exist in another array, but I am observing odd behavior when I use the splice and filter methods.
Can anyone explain the scenario below? Why is it happening like this in both cases, even though the same object is being altered on iteration?
Words
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
Removable Words
['four', 'two', 'eight']
let words = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
let removedWords = ['four', 'two', 'eight'];
words.forEach((word) => {
console.log(word);
if (removedWords.includes(word)) {
words = words.filter((removableWord) => removableWord !== word)
}
});
/* Output */
//one
//two
//three
//four
//five
//six
//seven
let words = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
let removedWords = ['four', 'two', 'eight'];
words.forEach((word, index) => {
console.log(word);
if (removedWords.includes(word)) {
words.splice(index, 1);
}
});
/* Output */
//one
//two
//four
//six
//seven
As mentioned in this Mozila document forEach() does not make a copy of the array before iterating. Shouldn't it behave the same as splice after filtering and assigning back to the original object?
Note: Just to add on this, the splice method makes changes on original array and the filter method creates a new copy of the array and doesn't alter the original array, but in the given example (after filtering), the result is assigned back to the original array.