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

5 Answers 5

1

Just use map()

var newArr = data.map(function(subArr){
  return subArr[0];
})
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

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

Comments

0

Here is a one liner that will do it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.