I'm working on a small exercise: The problem is that I want this:
=> ['kept','kept']
But instead, I keep getting this:
function keep(array, keeper) {
//This will return an array of undefined's and 'kept's
// =>[ 'kept', undefined, 'kept', undefined, undefined ]
matchingNumbers = array.map(function matching(element){
if (element === keeper) {
return element;
}
});
//Eliminate all undefined's from the matchingNumbers array
matchingLength = matchingNumbers.length;
for (var i = 1; i < matchingLength; i++) {
if(matchingNumbers[i] === undefined) {
(matchingNumbers.splice(i, 1));
}
}
return matchingNumbers;
}
keep(['kept', 'thirty', 'kept', 2, 1], 'kept')
I'm trying to splice off all of the undefined's in matchingNumbers with the for-loop, so why is there a last undefined remaining?