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

console.log(newArr);

方法二:

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

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

console.log(get1DArray(arrToConvert));

方法三:

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)

Dart:

var mylist = [1, 2, 3];
assert(mylist.contains(1));
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.

更多参考:

http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript

http://stackoverflow.com/questions/14824283/convert-a-2d-javascript-array-to-a-1d-array

 

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