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
  • 138,499
  • 22
  • 57
  • 95
Alaa Khalila
  • 169
  • 1
  • 11

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)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
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
  • 16