-1

let array =
[[`animal`,`carnivours`],
 [`cow`,`milk`],
 [`plant`,`small`],
 [`fish`,`tank`]]
 
 console.log(array[0]);

as I know if I want to fetch first value from array I have to use array[0] to get all the first name from the array but here I am getting first array from array list as my

expected value is like this

animal
cow
plant
fish

any simplest way to fetch all the first name from the list like this array[0] or somewhat like this ?

  • 3
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+get+first+column+of+array) of [Get column from a two dimensional array](/q/7848004/4642212). – Sebastian Simon Jul 14 '21 at 03:14

3 Answers3

2

You can use Array#map to create a new array with the first elements of each inner array.

let array =
[[`animal`,`carnivours`],
 [`cow`,`milk`],
 [`plant`,`small`],
 [`fish`,`tank`]];
let res = array.map(x => x[0]);
console.log(res);
// or
console.log(array.map(([f]) => f));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You probably customize a column function that returns the ith column of the array:

Array.prototype.column = function(i) {
  try { 
    return this.map( x => x[i]);
  } catch (e) {
    // catch error: out of index or null array ....
    console.log(e);
  }
}

let array =
[[`animal`,`carnivours`],
 [`cow`,`milk`],
 [`plant`,`small`],
 [`fish`,`tank`]];
  
console.log(array.column(0))
console.log(array.column(1))
Pylon
  • 698
  • 6
  • 9
0
 let array =
[[`animal`,`carnivours`],
 [`cow`,`milk`],
 [`plant`,`small`],
 [`fish`,`tank`]]
 
for (let i = 0; i < array.length; i++) {
  console.log(array[i][0]);
}

https://www.codeply.com/p/XrUKcnlLZQ