简体   繁体   English

将单元素数组的Javascript数组转换为一维数组

[英]Convert Javascript array of single-element arrays into 1d array

I'm stumped with this one. 我为此感到难过。 I have an array that looks like this: 我有一个看起来像这样的数组:

[[1],[2],[3],[4],[5]] [[1],[2],[3],[4],[5]]

(an array of single member arrays) (单成员数组的数组)

That array is given to me by google apps script, so I can't change the code that creates it. 该数组是由Google Apps脚本提供给我的,因此我无法更改创建它的代码。

i'm trying to get the index of a certain value. 我正在尝试获取某个值的索引。 I can't use indexOf because each value is an array of a single member (I tried array.indexOf([3]), but that doesn't work). 我不能使用indexOf,因为每个值都是单个成员的数组(我试过array.indexOf([3]),但这不起作用)。 Is there an easy way to convert it to a 1d array like this: 有没有一种简单的方法可以将其转换为一维数组,如下所示:

[1,2,3,4,5] [1,2,3,4,5]

I could always loop over the members of the original array, and copy it to a new array, but it seems like there should be a better way. 我总是可以遍历原始数组的成员,然后将其复制到新数组,但是似乎应该有更好的方法。

Just use map() 只需使用map()

var newArr = data.map(function(subArr){
  return subArr[0];
})

You can use reduce() : 您可以使用reduce()

 var a = [[1],[2],[3],[4],[5]]; var b = a.reduce( function( prev, item ){ return prev.concat( item ); }, [] ); console.log(b); 

Or concat : concat

 var a = [[1],[2],[3],[4],[5]]; var b = Array.prototype.concat.apply([], a ); console.log(b); 

Or map : map

 var a = [[1],[2],[3],[4],[5]]; var b = a.map( function(item){ return item[0]; } ); console.log(b); 

Found one answer, that seems simple enough, so I thought I would share it: 找到了一个答案,这似乎很简单,所以我想分享一下:

  var a = [[1], [2], [3], [4], [5], [6], [7]]; var b = a.map(function(value, index){return value[0];}); 

You can try to use map, which is similar to looping, but much cleaner: 您可以尝试使用map,它类似于循环,但更加简洁:

arr.map(function(val){return val[0];});

Or filter to directly filter the value you need: 或使用过滤器直接过滤所需的值:

var num = 1;
arr.filter(function(val){return val[0] == num;});

这是一个可以做的班轮:

array.toString().split(',').map(Number);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM