A multidimensional array to one dimension in JS

Source: Internet
Author: User

Method One: Use the array map () method, which runs the given function for each item in an array, and returns a list of the results of each function call.

Let arr = [1, [2, [[3,4],5],6]];function Onedimensionalarray (arr) {        "). Split (','//  Convert the array to a string and then comma-delimited to array let        arr2 = Arr1.map (function (x            ) {return number (x);        });         return arr2;} Console.log (Onedimensionalarray (arr));

Law two: Using apply combined with concat, the disadvantage is that only two-dimensional to one-dimensional, multi-dimensional array is wrong.

Let arr = [1,[2,3],[4,5]];console.log ([].concat.apply ([],arr)];

Method Three: Convert an array to a string and then to an array, with the disadvantage that each item in the array is a string

Let arr = [1,[2,[[3,4],5],6]];let arr2 = Arr.join (', '). Split (', '); Console.log (ARR2);//["1", "2", "3", "4", "5", "6"]

Or
Let C=[1,3,4,5,[6,[0,1,5],9],[2,5,[1,5]],[5]];
Console.log (C.tostring (). Split (', '))

Law IV: Recursion

Let arr = [1, [2, [[3456= [];function Onedimensionalarray (arr) {    for0; i < arr.length; i++) {        if  (Array.isarray (Arr[i])) {            Onedimensionalarray (arr[i]);         Else {            newarr.push (arr[i]);        }     // [1, 2, 3, 4, 5, 6]

Law V: reduce+ recursion

    Use strict ';    Let arr = [1,[2,[[3,4],5],6]];    Const FLATTEN = arr = Arr.reduce (            (acc,val) = Acc.concat (Array.isarray (val)? Flatten (val): Val), []    )    Console.log (Flatten (arr));//[1, 2, 3, 4, 5, 6]

A multidimensional array to one dimension in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.