[英]Map the first element of each array of an array of arrays in Javascript
I have an array of arrays like this:我有一个 arrays 的数组,如下所示:
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"]
.我想得到一个只包含每个数组的第一个元素的数组,如下所示: ["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?有什么建议么?
You could return just the first elementn of x
, an element of the outer array. 您可以只返回x
的第一个elementn,即外部数组的元素。
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. 您的x
本身是一个数组。 So you need not to touch myData again inside. 因此,您无需在内部再次触摸myData。
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. 使用实际的代码return [myData[x][0]]
,您将返回undefined
,因为x
是迭代项,因此它是一个array
而不是索引。
And using the wrapping []
is useless here, it's a destructing syntax, we don't need it here. 而且在这里使用wrapping []
是没有用的,这是一种破坏语法,在这里我们不需要它。
You should only return item[0]
in each iteration: 您应该在每次迭代中仅返回item[0]
:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.