A multidimensional array to one dimension in JS

Source: Internet
Author: User
Tags array to string

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.

var arr = [1,[2,[[3,4],5],6]]; function Unid (arr) {        var arr1 = (arr + '). Split (', ');   Convert the array to string and then comma-delimited to array        var arr2 = Arr1.map (function(x)            {  return number (x);        });         return arr2;} Console.log (Unid (ARRA));

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

Const 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

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

Law IV: Recursion

var arr = [1,[2,[[3,4],5],6]]; var newArr = [];     function Fun (arr) {        for (var i=0;i<arr.length;i++) {            if( Array.isarray (Arr[i]) {fun                (arr[i]);            } Else {                newarr.push (arr[i]);            }        }    } Fun (arr); Console.log (NEWARR); // [1, 2, 3, 4, 5, 6]

Law V: reduce+ recursion

    Use strict ';    var 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.