-1

I am practicing the for-in statements.

I want to get all numbers bigger than five into a new array and print them to the console.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8];

let result=[];

for (var number in numbers){
    result.push (number => number > 5)
    console.log(result);
}
whatever
  • 157
  • 7
  • Don't use `for...in...` for arrays. That's for iterating the properties of an object only. – Andreas Jul 12 '21 at 10:02
  • what would I use then – whatever Jul 12 '21 at 10:03
  • 1
    `.push()` adds the parameter into the array it is called on. What do you expect to happen with `.push(number => number > 5)`? That whole construct should be a `.filter()` call only. – Andreas Jul 12 '21 at 10:03
  • A regular `for` loop, `.forEach()`, `.filter()`, `.reduce()`, `while`, ... - what ever fits your needs (which would be `.filter()` in this case) – Andreas Jul 12 '21 at 10:04
  • I know how to do it with filter ```const result = numbers.filter( number => number > 5 ) console.log(result)``` – whatever Jul 12 '21 at 10:04
  • `let result = numbers.filter(number => number > 5)` might be what you are looking for. – Hao Wu Jul 12 '21 at 10:05
  • 2
    Warning : `for( ... in ... )` gives you the _index_ of the elements. You won't be getting `1, 2, 3, 4` but `0, 1, 2, 3` (the index of the number 1 in your array is 0). If you want the elements themselves, use `for( ... of ...)` – Jeremy Thille Jul 12 '21 at 10:05

1 Answers1

1

It is recommended not to use for..in with arrays.

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties. - MDN

You can use for..of with Arrays. Since arrays are iterable objects.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8];

let result = [];

for (let num of numbers) {
  if (num > 5) result.push(num);
}

console.log(result);

Alternatively, you can use filter to get the numbers that is greater than 5

let numbers = [1, 2, 3, 4, 5, 6, 7, 8];

let result = numbers.filter((num) => num > 5);

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 1
    Does this really deserve an answer because there isn't already another question with the same topic here on SO? – Andreas Jul 12 '21 at 10:04