I am using Visual Studio Code. I am trying to return an array with only odd numbers using JavaScript. This is the code:
function oddCouple(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
delete arr[i];
}
}
return arr;
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
This is what I am getting. I do not want the empty items, just odd numbers.
[ <2 empty items>, 7, <1 empty item>, 1, 3, 7, 5 ]
You need to use splice()
instead of delete because delete
doesn't change the length of the array. But be careful using splice()
in a for
loop because you alter the array as you're looping through it, which doesn't work well.
An alternative is to loop backwards:
function oddCouple(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] % 2 == 0) {
arr.splice(i, 1);
}
}
return arr;
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
Of course a still better alternative is to use filter()
, but note this doesn't change the original array.
function oddCouple(arr) {
return arr.filter(i => i % 2)
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
The delete
function removes the content of the item but keeps an empty slot.
You need the splice
method to remove an element without leaving an empty slot.
arr.splice(i, 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With