Currently, I am looping through an array of strings using forEach() method to check if each element's length is even or odd. If the length is even, I am removing it using splice().
Although my conditions seem correct, when I look at the input and output below, I notice that despite expecting the even, two-character word to be spliced out, it still appears in the return array.
Here's the code snippet:
function filterOddLengthWords(words) {
words.forEach(function(element, index) {
if (element.length % 2 === 0) {
words.splice(index, 1);
}
})
return words;
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output); // --> [ 'there', 'is', 'now' ]
I can identify where the mistake lies but I need help figuring out how to rectify it. One possible solution could involve creating an empty array at the start of the function and then checking each element against the opposite condition, adding the positive results using push(). However, this method seems less efficient, so I'm hoping there might be a way to optimize my original approach. Thank you in advance for any advice.