Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 960
Samurai Jack Avatar asked Nov 21 '17 14:11

Samurai Jack


People also ask

How do you find the first n elements of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.

Is first element of array JavaScript?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .


2 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);
like image 180
Nina Scholz Avatar answered Oct 10 '22 19:10

Nina Scholz


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);
like image 26
Suresh Atta Avatar answered Oct 10 '22 18:10

Suresh Atta