Javascript: 二维数组转一维数组(合并数组) Convert a 2D array to a 1D array

Here, I’m trying to convert arrToConvert to a 1D array.

var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];

console.log(get1DArray(arrToConvert)); //print the converted array

function get1DArray(2dArr){
    //concatenate each element of the input into a 1D array, and return the output
    //what would be the best way to implement this function?


解决方案 Answers



Try .concat():

var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var newArr = [];

for(var i = 0; i < arrToConvert.length; i++)
    newArr = newArr.concat(arrToConvert[i]);




var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];

function get1DArray(arr){
    return arr.join().split(",");




Modern browsers have Array#indexOf, which can do that. Even newer browsers have Array#includes, which does exactly that, but unfortunately it’s not widely supported. Older browsers can be supported using this polyfill.

jQuery offers $.inArray, which is functionally equivalent to Array#indexOf.

underscore.js, a JavaScript utility library, offers _.contains(list, value), alias _.include(list, value), both of which use indexOf internally if passed a JavaScript array.

Some other frameworks offer similar methods:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.


Languages that compile to JavaScript

In CoffeeScript, the in operator is the equivalent of contains:

a = [1, 2, 3, 4]
alert(2 in a)


var mylist = [1, 2, 3];
assert(mylist.indexOf(1) == 0);



The shortest version:

my1dArray = [].concat.apply([], my2dArray);

But this is cleaner to me:

my1dArray = Array.prototype.concat.apply([], my2dArray);

fun.apply takes an array of arguments as the 2nd parameter and uses them to call fun.





本文: Javascript: 二维数组转一维数组(合并数组) Convert a 2D array to a 1D array

Leave a Reply