Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  3] [ 7]  / answers: 1 / hits: 119478  / 12 Years ago, tue, february 12, 2013, 12:00:00

I want to convert a 2D JavaScript array to a 1D array, so that each element of the 2D array will be concatenated into a single 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?
}

More From » javascript

 Answers
27

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

[#80280] Sunday, February 10, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;