TransWikia.com

Loop nested array and return values by index

Stack Overflow Asked by Jordan Starrk on February 11, 2021

I have a nested array that holds a handful of coordinates. I am trying to loop the nested array and log the values of each coordinate.

I can get it working in Python, but I need it in JavaScript. Here is how it works in python:

list_of_coordinates = [(100, 98), (200, 78)]
for i in list_of_coordinates:
    x_coord = i[0]
    y_coord = i[1]
    print(x_coord, y_coord)

The output of the above is:

100 98
200 78

When I try to do this in Javascript I get the output of 0 and 1… not the actual coordinate values.

let listOfCoordinates = [[100, 0], [200, 1]];
for (const i in listOfCoordinates) {
    let xCoord = i[0];
    let yCoord = i[1];
    console.log(xCoord, yCoord);
}

The output of this is

0 undefined
1 undefined

4 Answers

You could take for ... of statement and a destructuring assignment to the wanted variables.

let listOfCoordinates = [[100, 0], [200, 1]];

for (const [xCoord, yCoord] of listOfCoordinates) {
    console.log(xCoord, yCoord);
}

Answered by Nina Scholz on February 11, 2021

forEach way, with deconstruction of the input.

let listOfCoordinates = [[100, 0], [200, 1]];

listOfCoordinates.forEach(([xCoord, yCoord]) => console.log(xCoord, yCoord));

Answered by Taplar on February 11, 2021

Correct way, if you want to continue to use for...in:

const listOfCoordinates = [[100, 0], [200, 1]];
for (let i in listOfCoordinates) {
    let xCoord = listOfCoordinates[i][0];
    let yCoord = listOfCoordinates[i][1];
    console.log(xCoord, yCoord);
}

Because you named the variable "i", which is often short for "index", I thought you'd want it to be an index, which would use the "in" form.

The for...of form returns the values. It could be written like so:

const listOfCoordinates = [[100, 0], [200, 1]];
    for (let coord of listOfCoordinates) {
        let xCoord = coord[0];
        let yCoord = coord[1];
        console.log(xCoord, yCoord);
    }

Answered by ADJenks on February 11, 2021

You should use for..of instead as the following:

let listOfCoordinates = [[100, 0], [200, 1]];
for (const i of listOfCoordinates) {
    let xCoord = i[0];
    let yCoord = i[1];
    console.log(xCoord, yCoord);
}

See from the documentation:

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

Answered by norbitrial on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP