-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 ?

1

3 Answers 3

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));

Sign up to request clarification or add additional context in comments.

2 Comments

thank you as i was already knowing this method but trying to minimize the code i guess i have to go with method :) but thank you
array.map(x => x[0]); is not very much code!
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))

Comments

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

1 Comment

Why would you ever do this, rather than the map function!!??