0

I'm stumped with this one. I have an array that looks like this:

[[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.

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). Is there an easy way to convert it to a 1d array like this:

[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.

  • 1
    Possible duplicate of [Merge/flatten an array of arrays in JavaScript?](http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript) – OJay Jan 18 '17 at 00:58

5 Answers5

1

Just use map()

var newArr = data.map(function(subArr){
  return subArr[0];
})
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You can use reduce():

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

Or concat:

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

Or map:

var a = [[1],[2],[3],[4],[5]];
var b = a.map( function(item){ return item[0]; } );
console.log(b);
MT0
  • 143,790
  • 11
  • 59
  • 117
0

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];});
0

You can try to use map, which is similar to looping, but much cleaner:

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;});
poushy
  • 1,114
  • 11
  • 17
0

Here is a one liner that will do it:

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

Patrick Murphy
  • 2,311
  • 14
  • 17