1

I'm trying to write a function (onlyOddNumbers) that accepts an array of numbers and returns a new array with only the odd numbers, it's working but the problem is I'm getting strings in the new array instead of numbers, why this happen ?

enter image description here

let oddNumbersOnly=[]
const filter = function (numbers) {
  for (number in numbers){
    if(number %2 !==0){
      oddNumbersOnly.push(number)
    }
  } return oddNumbersOnly;
};
Nick
  • 123,192
  • 20
  • 49
  • 81
Alaa Khalila
  • 149
  • 1
  • 10

2 Answers2

1

use for of instead of for in then convert your num to string

const filter = function(numbers) {
  let oddNumbersOnly = []
  for (let number of numbers) {
    if (number % 2 !== 0) {
      oddNumbersOnly.push(number.toString())
    }
  }
  return oddNumbersOnly;
};
const arr = [1, 2, 3, 4, 5, 6];
const result = filter(arr)
console.log(result)
Eugen Sunic
  • 12,218
  • 8
  • 60
  • 78
0

let num = [0, 1, 2, 3, 4, 5, 6];
let oddNumbersOnly = num.filter(numb=>numb%2 !==0);
console.log(oddNumbersOnly);

javaScript has an inbuilt es6 filter function. It is shorter and retain the datatype. You may try this.

atomty
  • 187
  • 2
  • 14