Map the first element of each array of an array of arrays in Javascript

Viewed 10753

I have an array of arrays like this:

myData = [
          ["name1", 34.1, 43.1, 55.2],
          ["name2", 5.3, 23.6, 40.9],
          ["name3", 43.5, 77.8, 22.4]
         ];

I want to get an array containing only the first element of each array like this: ["name1", "name2", "name3"].

I tried to do it like this but doesn't work:

var arrayTitle = myData.map(function(x) {
    return [myData[x][0]];
});

Any suggestions?

4 Answers

You could return just the first elementn of x, an element of the outer array.

var myData = [["name1", 34.1, 43.1, 55.2], ["name2", 5.3, 23.6, 40.9], ["name3", 43.5, 77.8, 22.4]],
    arrayTitle = myData.map(function(x) {
        return x[0];
    });

console.log(arrayTitle);

Your x itself is an array. So you need not to touch myData again inside.

var arrayTitle = myData.map(function(x) {
    return x[0];
});

or with a traditional loop

myData = [
          ["name1", 34.1, 43.1, 55.2],
          ["name2", 5.3, 23.6, 40.9],
          ["name3", 43.5, 77.8, 22.4]
         ];


var arrayTitle = [];

for(var k in myData)
 arrayTitle.push(myData[k][0]);
 
 console.log(arrayTitle);

With your actual code return [myData[x][0]], you are returning undefined, because x is the iterated item, so it's an array and not an index.

And using the wrapping [] is useless here, it's a destructing syntax, we don't need it here.

You should only return item[0] in each iteration:

var res = myData.map(function(arr) {
  return arr[0];
});

Demo:

myData = [
  ["name1", 34.1, 43.1, 55.2],
  ["name2", 5.3, 23.6, 40.9],
  ["name3", 43.5, 77.8, 22.4]
];


var res = myData.map(function(arr) {
  return [arr[x][0]];
});
console.log(res);

This could be the shortest answer:

var res = myData.map(a => a[0])

Related