Search code examples
javascriptarraysmethodscycle

JS: Print main diagonal of array using array methods


How to print the main diagonale of array without using cycle for(...) but using array methods instead?


 const arr = [
 [1,6,8,-1],
 [0,2,-6,5],
 [0,-5,3,6],
 [9,-1,1,0] ];

Here elements arr[0][0] = 1, arr[1][1]=2, arr[2][2]=3, arr[3][3]=0 are elements of the main diagonale. We can print them using cycle for:


for (let i=0;i<arr.length;i++)
{
    console.log(arr[i][i]);
}

But is there a possibility to print them using methods .forEach .map or another one?


Solution

  • You can use Array.prototype.map but essentially they use the loops inside:

    var a = [
     [1,6,8,-1],
     [0,2,-6,5],
     [0,-5,3,6],
     [9,-1,1,0] ];
    
    var r = a.map((v, i) => v[i]);
    
    console.log(r);