-1

I've spent an embarrassing amount of time on this question only to realize my function is only right 50% of the time. So the goal here is to return only the odd numbers of all the numbers in between the two arguments. (for instance if the arguments are 1 and 5 i'd need to return 2 & 3) the function I wrote is completely dependent on the first argument. if it's even my function will return odds, but if the first number is odd it'll return evens. does anyone know how i can fix this?

function oddNumbers(l, r) {
  const arr = [];
  const theEvens = [];
    for (let i= l; i<r; i++) {
      arr.push(i)
    }
  console.log(arr)
  for (let i= 0; i < arr.length; i+= 2 ) {
      const evens = arr[0] + i;
      theEvens.push(evens);
  }
  theEvens.forEach(item => arr.splice(arr.indexOf(item), 1));
  console.log(arr)
}

oddNumbers(2, 20);
Ishmael
  • 21
  • 5

3 Answers3

2

I modified the code a bit to return only odd numbers

We use the % operator that behaves like the remainder operator in math:

so when we say i % 2 if the number is even the result of the operation will be 0

but when the "i" is an odd number the result will be 1

so now we can filter the even from the odd numbers using this operation

function oddNumbers(l, r) {
  const arr = [];
    for (let i= l; i<r; i++) {
      if(i % 2 !== 0) arr.push(i);
    }
  console.log(arr);
}

oddNumbers(2, 20);
Ahmed Gaafer
  • 1,603
  • 9
  • 26
  • While this solution works, it's mostly code and doesn't explain why it works. It would help if you expanded on the use of the [remainder operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) which op didn't use in their code. – Robert Corponoi Jan 18 '21 at 16:00
  • 1
    added a short explinaton – Ahmed Gaafer Jan 18 '21 at 16:05
0

You can loop from initial to end parameters and get odd numbers using modulo, try this:

let result = [];
let returnOdd = (n1, n2) => {
    for(i = n1; i < n2; i++){
        if(i % 2 != 0){
            result.push(i)
        }
    }
    return result;
}

console.log(returnOdd(2, 20));
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

You could use the filter method.

This method creates a new array based on the condition it has. In this case it will to go through all the numbers in the array, and check if the number is odd (though the remainder operator).

For example:

1 % 2 = 1 ( true, keep in the new array )
2 % 2 = 0 ( false ignore in the new array ) 

function OddNumbers(start, end) {
  // Create an array from the given range
  const nums = Array(end - start + 1).fill().map((_, idx) => start + idx);
  // Use filter to return the odd numbers via the % operator
  return nums.filter(num => num % 2);
}

console.log(OddNumbers(2,20))
S.Visser
  • 4,645
  • 1
  • 22
  • 43