-5

I've been struggling with finding an Javascript equivalent of Python's "for x in y". For instance, I want to push numbers that are even to an empty array, but I don't know how to script the code to do so. I've been doing this:

var numbers = [ 1, 2, 3, 4, 5]
var even = []
for(var x = 0; x < numbers.length; x++){
     if(x % 2 == 0){
         even.push(x)
     }
}

same thing for strings too if numbers were instead strings:

var numbers = [ "one", "two", "three"]
var even = []
for(var x = 0; x < numbers.length; x++){
     if(x == "two"){
         even.push(x)
     }
}

i noticed any time I typed it up, it only showed x as the index of the array, but I want to access the elements.

3 Answers3

2

for (let x of numbers) JS statement is what you are looking for.

x will be iterating over the values and not indexes.

const numbers = [ 1, 2, 3, 4, 5]
const even = []
for(const x of numbers){
     if(x % 2 === 0){
         even.push(x)
     }
}

P.S.

even = numbers.filter(el => el % 2 === 0) can be also used and is much simpler.

You can find the docs here.

Vitalii
  • 2,071
  • 1
  • 4
  • 5
0

When you push x to the list, it will push 2,4,...,length of the first list. You need to use

var numbers = [ 1, 2, 3, 4, 5]
var even = []
for(var x = 0; x < numbers.length; x++){
    if(x % 2 == 0){
        even.push(numbers[x])
    }
}
Onur
  • 164
  • 1
  • 18
0

If you use a generator and a for..of loop you can achieve something quite similar to the Python syntax.

function* filter(predicate, iterable) {
  for (let item of iterable)
    if (predicate(item))
      yield item;
}

const isEven = x => x % 2 === 0;


var numbers = [1, 2, 3, 4, 5]
var even = []
for(let x of filter(isEven, numbers)){
  even.push(x)
}

console.log(even);

For more information, you can check the MDN article on iterators and generators.

VLAZ
  • 26,331
  • 9
  • 49
  • 67