2

I need to remove the even numbers for this array

function removeEvens(numbers) {

}

/* Do not modify code below this line */

const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers, `<-- should equal [1, 3, 5]`);
Mark Bolusmjak
  • 23,606
  • 10
  • 74
  • 129
  • Does this answer your question? [Javascript - Filtering even numbers](https://stackoverflow.com/questions/51876350/javascript-filtering-even-numbers) – Tomerikoo Feb 22 '23 at 08:03

3 Answers3

4

The first step is how you check for evens - you can do this using the modulus operator (%) to see if the remainder when divided by 2 is 0, meaning that the number is even. Next you can filter the array to include only the numbers which pass this test:

function removeEvens(numbers) {
    return numbers.filter(n => n % 2 !== 0); // if a number is even, remove it
}

const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers);
awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • Is 3.1 even? :) – Joundill May 08 '20 at 01:09
  • 2
    @Joundill well it wasn't clearly specified whether there can be floats in the Array, but I updated my answer to not make this assumption. Although, it doesn't even make sense to be checking for the parity of an irrational number so I'm sure this won't have an effect – awarrier99 May 08 '20 at 01:10
0

You can use .filter to do this with one line.

function removeEvens(numbers) {
    return numbers.filter(n => n % 2 !== 0);
}


const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers, '<-- should equal [1, 3, 5]');
Joundill
  • 6,828
  • 12
  • 36
  • 50
0

Here is the code:

function removeEvens(numbers) {
  return numbers.filter(n => n % 2 == 1);
}

/* Do not modify code below this line */

const oddNumbers = removeEvens([1, 2, 3, 4, 5]);
console.log(oddNumbers);
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61