Anderson Green
Anderson Green

Reputation: 31810

Iterate over a JavaScript array without using nested for-loops

I've been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. Is there any way to print each element in a multidimensional array without using nested for-loops?

http://jsfiddle.net/mKsDW/

var arr = [[1, 5],[7, 4]];
for(var i in arr){
    alert(i); //this displays "0", then displays "1",
    //instead of printing each element in the array
    //how can I make it print each element in each 2D array instead,
    //without using nested for-loops for each dimension of the array?
}

Upvotes: 4

Views: 16299

Answers (3)

trincot
trincot

Reputation: 350310

Since more array methods were introduced you can use flat():

const arr = [[1, 5],[7, 4]];
for (const val of arr.flat()) console.log(val);

But flat creates a new array. To avoid that you can use ECMAScript iterator helper methods:

const arr = [[1, 5],[7, 4]];
for (const val of arr.values().flatMap(x => x)) console.log(val);

Upvotes: 1

ZER0
ZER0

Reputation: 25322

If you don't want to use nested loops, you can either flat the array or use a recursive function. Something like:

arr.forEach(function each(item) {
  if (Array.isArray(item))
    item.forEach(each);
  else
    console.log(item)
});

Upvotes: 6

user1106925
user1106925

Reputation:

Sounds like the issue is that you may have a nesting of arbitrary depth. In that case, use a recursive function.

function printArray(arr) {
    for (var i = 0; i < arr.length; i++)
        if (Array.isArray(arr[i]))
            printArray(arr[i])
        else
            console.log(arr[i])
}

The Array.isArray will need a shim for older browsers.

if (!Array.isArray)
    Array.isArray = function(o) {
        return !!o && Object.prototype.toString.call(o) === "[object Array]"
    }

Upvotes: 16

Related Questions