Reputation: 45
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.
Upvotes: 0
Views: 66
Reputation: 167981
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);
Upvotes: 1
Reputation: 2329
Here is a one liner that will do it:
array.toString().split(',').map(Number);
Upvotes: 0
Reputation: 1134
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;});
Upvotes: 0
Reputation: 45
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];});
Upvotes: 0
Reputation: 171669
Just use map()
var newArr = data.map(function(subArr){
return subArr[0];
})
Upvotes: 1