9

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?

1
  • x is an element of the array and not an index. And don't wrap the return value in an array [] Commented Nov 21, 2017 at 14:16

4 Answers 4

8

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

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

Comments

2

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

2 Comments

for...in... is for objects
for...in... will return the index of the array. It returns the key for objects.
1

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

Comments

0

This could be the shortest answer:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.