skip to Main Content

I have a jagged array here, and I want to fetch the column of this array of arrays, and make the column into another array:

var array = [
    [0, 1, z, 0],
    [1, 0, s, 1],
    [0, 1, x, 0],
    [1, 0, a, 1],
];

So that the new array is:

var expectedOutput = [z, s, x, a];

How would I go about that?

2

Answers


  1. You can use the .map function in JS for this and extract the 2nd value of each array into a new array.

    var expectedOutput = array.map(item => item[2]);

    The .map function works a bit like a for loop where it puts each entry into a function and returns a value.

    Login or Signup to reply.
  2. Ot as a function, getColumn

    var array = [
      [0, 1, 'z', 0],
      [1, 0, 's', 1],
      [0, 1, 'x', 0],
      [1, 0, 'a', 1],
    ];
    
    
    function getColumn(arr, index) {
      return arr.map(row => row[index])
    }
    
    console.log(getColumn(array, 2))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search