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?
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With