Sorting a multidimensional array in javascript?












1














I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks



     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
var nestedArrOne = nestedArr[0];
var nestedArrTwo = nestedArr[1];
var newArr = nestedArrOne.concat(nestedArrTwo);
function showAll(){
for(var i=0; i<newArr.length; i++){
for(var j=0; j<newArr[i].length; j++){
console.log(newArr[i][j]);
}
}
}

showAll();









share|improve this question
























  • This is called "flatten", not "sort" around these parts ;) Look it up.
    – georg
    Jun 8 '17 at 8:57










  • Hi @Sen123 I believe, you should post the question in LINK
    – Sudipta Mondal
    Jun 8 '17 at 8:57










  • You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
    – Brett East
    Jun 8 '17 at 8:59










  • btw, you don't sort something.
    – Nina Scholz
    Jun 8 '17 at 9:01










  • See also stackoverflow.com/a/44103808/1647737
    – le_m
    Jun 8 '17 at 10:05
















1














I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks



     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
var nestedArrOne = nestedArr[0];
var nestedArrTwo = nestedArr[1];
var newArr = nestedArrOne.concat(nestedArrTwo);
function showAll(){
for(var i=0; i<newArr.length; i++){
for(var j=0; j<newArr[i].length; j++){
console.log(newArr[i][j]);
}
}
}

showAll();









share|improve this question
























  • This is called "flatten", not "sort" around these parts ;) Look it up.
    – georg
    Jun 8 '17 at 8:57










  • Hi @Sen123 I believe, you should post the question in LINK
    – Sudipta Mondal
    Jun 8 '17 at 8:57










  • You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
    – Brett East
    Jun 8 '17 at 8:59










  • btw, you don't sort something.
    – Nina Scholz
    Jun 8 '17 at 9:01










  • See also stackoverflow.com/a/44103808/1647737
    – le_m
    Jun 8 '17 at 10:05














1












1








1







I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks



     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
var nestedArrOne = nestedArr[0];
var nestedArrTwo = nestedArr[1];
var newArr = nestedArrOne.concat(nestedArrTwo);
function showAll(){
for(var i=0; i<newArr.length; i++){
for(var j=0; j<newArr[i].length; j++){
console.log(newArr[i][j]);
}
}
}

showAll();









share|improve this question















I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks



     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
var nestedArrOne = nestedArr[0];
var nestedArrTwo = nestedArr[1];
var newArr = nestedArrOne.concat(nestedArrTwo);
function showAll(){
for(var i=0; i<newArr.length; i++){
for(var j=0; j<newArr[i].length; j++){
console.log(newArr[i][j]);
}
}
}

showAll();






javascript arrays sorting for-loop multidimensional-array






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 2:27









Cœur

17.4k9102143




17.4k9102143










asked Jun 8 '17 at 8:53









Sen123

185




185












  • This is called "flatten", not "sort" around these parts ;) Look it up.
    – georg
    Jun 8 '17 at 8:57










  • Hi @Sen123 I believe, you should post the question in LINK
    – Sudipta Mondal
    Jun 8 '17 at 8:57










  • You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
    – Brett East
    Jun 8 '17 at 8:59










  • btw, you don't sort something.
    – Nina Scholz
    Jun 8 '17 at 9:01










  • See also stackoverflow.com/a/44103808/1647737
    – le_m
    Jun 8 '17 at 10:05


















  • This is called "flatten", not "sort" around these parts ;) Look it up.
    – georg
    Jun 8 '17 at 8:57










  • Hi @Sen123 I believe, you should post the question in LINK
    – Sudipta Mondal
    Jun 8 '17 at 8:57










  • You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
    – Brett East
    Jun 8 '17 at 8:59










  • btw, you don't sort something.
    – Nina Scholz
    Jun 8 '17 at 9:01










  • See also stackoverflow.com/a/44103808/1647737
    – le_m
    Jun 8 '17 at 10:05
















This is called "flatten", not "sort" around these parts ;) Look it up.
– georg
Jun 8 '17 at 8:57




This is called "flatten", not "sort" around these parts ;) Look it up.
– georg
Jun 8 '17 at 8:57












Hi @Sen123 I believe, you should post the question in LINK
– Sudipta Mondal
Jun 8 '17 at 8:57




Hi @Sen123 I believe, you should post the question in LINK
– Sudipta Mondal
Jun 8 '17 at 8:57












You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
– Brett East
Jun 8 '17 at 8:59




You have a couple of issues with your code, but here's one to get started with: When you pass an index to an array, you get the next item in the array, not the next nested level. So nestedArr only has one item in it [[1,2],[3,4],[5,6]] which is nestedArr[0] - nestedArr[1] isn't anything.
– Brett East
Jun 8 '17 at 8:59












btw, you don't sort something.
– Nina Scholz
Jun 8 '17 at 9:01




btw, you don't sort something.
– Nina Scholz
Jun 8 '17 at 9:01












See also stackoverflow.com/a/44103808/1647737
– le_m
Jun 8 '17 at 10:05




See also stackoverflow.com/a/44103808/1647737
– le_m
Jun 8 '17 at 10:05












3 Answers
3






active

oldest

votes


















0














You could iterate the nested array and check if the item is an array, then call the function again for the inner array.






function iter(array) {
var i; // declare index
for (i = 0; i < array.length; i++) { // iterate array
if (Array.isArray(array[i])) { // check if item is an array
iter(array[i]); // if so, call iter with item
continue; // and continue the loop
}
console.log(array[i]); // the wanted output
}
}

var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
iter(nestedArr);








share|improve this answer





























    0














    The recursive function could be used to flatten the array.






    let isArray = val => val.constructor === Array

    let log = val => console.log(val)

    let flatten = val =>
    val
    .reduce((acc, cur) =>
    isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
    )


    // Running examples
    let arrA = [[[1,2],[3,4]],[[5,6]]]
    flatten(arrA).forEach(log)

    log('-------------------')

    let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
    flatten(arrB).forEach(log)








    share|improve this answer































      0














      A fancy Haskellesque approach with "pattern matching by rest operator" could be.






      var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
      na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
      fa = flat(na);
      console.log(...fa);








      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44431043%2fsorting-a-multidimensional-array-in-javascript%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        You could iterate the nested array and check if the item is an array, then call the function again for the inner array.






        function iter(array) {
        var i; // declare index
        for (i = 0; i < array.length; i++) { // iterate array
        if (Array.isArray(array[i])) { // check if item is an array
        iter(array[i]); // if so, call iter with item
        continue; // and continue the loop
        }
        console.log(array[i]); // the wanted output
        }
        }

        var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
        iter(nestedArr);








        share|improve this answer


























          0














          You could iterate the nested array and check if the item is an array, then call the function again for the inner array.






          function iter(array) {
          var i; // declare index
          for (i = 0; i < array.length; i++) { // iterate array
          if (Array.isArray(array[i])) { // check if item is an array
          iter(array[i]); // if so, call iter with item
          continue; // and continue the loop
          }
          console.log(array[i]); // the wanted output
          }
          }

          var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
          iter(nestedArr);








          share|improve this answer
























            0












            0








            0






            You could iterate the nested array and check if the item is an array, then call the function again for the inner array.






            function iter(array) {
            var i; // declare index
            for (i = 0; i < array.length; i++) { // iterate array
            if (Array.isArray(array[i])) { // check if item is an array
            iter(array[i]); // if so, call iter with item
            continue; // and continue the loop
            }
            console.log(array[i]); // the wanted output
            }
            }

            var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
            iter(nestedArr);








            share|improve this answer












            You could iterate the nested array and check if the item is an array, then call the function again for the inner array.






            function iter(array) {
            var i; // declare index
            for (i = 0; i < array.length; i++) { // iterate array
            if (Array.isArray(array[i])) { // check if item is an array
            iter(array[i]); // if so, call iter with item
            continue; // and continue the loop
            }
            console.log(array[i]); // the wanted output
            }
            }

            var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
            iter(nestedArr);








            function iter(array) {
            var i; // declare index
            for (i = 0; i < array.length; i++) { // iterate array
            if (Array.isArray(array[i])) { // check if item is an array
            iter(array[i]); // if so, call iter with item
            continue; // and continue the loop
            }
            console.log(array[i]); // the wanted output
            }
            }

            var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
            iter(nestedArr);





            function iter(array) {
            var i; // declare index
            for (i = 0; i < array.length; i++) { // iterate array
            if (Array.isArray(array[i])) { // check if item is an array
            iter(array[i]); // if so, call iter with item
            continue; // and continue the loop
            }
            console.log(array[i]); // the wanted output
            }
            }

            var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
            iter(nestedArr);






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 8 '17 at 8:59









            Nina Scholz

            175k1388152




            175k1388152

























                0














                The recursive function could be used to flatten the array.






                let isArray = val => val.constructor === Array

                let log = val => console.log(val)

                let flatten = val =>
                val
                .reduce((acc, cur) =>
                isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                )


                // Running examples
                let arrA = [[[1,2],[3,4]],[[5,6]]]
                flatten(arrA).forEach(log)

                log('-------------------')

                let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                flatten(arrB).forEach(log)








                share|improve this answer




























                  0














                  The recursive function could be used to flatten the array.






                  let isArray = val => val.constructor === Array

                  let log = val => console.log(val)

                  let flatten = val =>
                  val
                  .reduce((acc, cur) =>
                  isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                  )


                  // Running examples
                  let arrA = [[[1,2],[3,4]],[[5,6]]]
                  flatten(arrA).forEach(log)

                  log('-------------------')

                  let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                  flatten(arrB).forEach(log)








                  share|improve this answer


























                    0












                    0








                    0






                    The recursive function could be used to flatten the array.






                    let isArray = val => val.constructor === Array

                    let log = val => console.log(val)

                    let flatten = val =>
                    val
                    .reduce((acc, cur) =>
                    isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                    )


                    // Running examples
                    let arrA = [[[1,2],[3,4]],[[5,6]]]
                    flatten(arrA).forEach(log)

                    log('-------------------')

                    let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                    flatten(arrB).forEach(log)








                    share|improve this answer














                    The recursive function could be used to flatten the array.






                    let isArray = val => val.constructor === Array

                    let log = val => console.log(val)

                    let flatten = val =>
                    val
                    .reduce((acc, cur) =>
                    isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                    )


                    // Running examples
                    let arrA = [[[1,2],[3,4]],[[5,6]]]
                    flatten(arrA).forEach(log)

                    log('-------------------')

                    let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                    flatten(arrB).forEach(log)








                    let isArray = val => val.constructor === Array

                    let log = val => console.log(val)

                    let flatten = val =>
                    val
                    .reduce((acc, cur) =>
                    isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                    )


                    // Running examples
                    let arrA = [[[1,2],[3,4]],[[5,6]]]
                    flatten(arrA).forEach(log)

                    log('-------------------')

                    let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                    flatten(arrB).forEach(log)





                    let isArray = val => val.constructor === Array

                    let log = val => console.log(val)

                    let flatten = val =>
                    val
                    .reduce((acc, cur) =>
                    isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
                    )


                    // Running examples
                    let arrA = [[[1,2],[3,4]],[[5,6]]]
                    flatten(arrA).forEach(log)

                    log('-------------------')

                    let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
                    flatten(arrB).forEach(log)






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 8 '17 at 9:48

























                    answered Jun 8 '17 at 9:35









                    shuaibird

                    36133




                    36133























                        0














                        A fancy Haskellesque approach with "pattern matching by rest operator" could be.






                        var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                        na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                        fa = flat(na);
                        console.log(...fa);








                        share|improve this answer


























                          0














                          A fancy Haskellesque approach with "pattern matching by rest operator" could be.






                          var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                          na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                          fa = flat(na);
                          console.log(...fa);








                          share|improve this answer
























                            0












                            0








                            0






                            A fancy Haskellesque approach with "pattern matching by rest operator" could be.






                            var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                            na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                            fa = flat(na);
                            console.log(...fa);








                            share|improve this answer












                            A fancy Haskellesque approach with "pattern matching by rest operator" could be.






                            var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                            na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                            fa = flat(na);
                            console.log(...fa);








                            var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                            na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                            fa = flat(na);
                            console.log(...fa);





                            var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : ;
                            na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
                            fa = flat(na);
                            console.log(...fa);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 8 '17 at 11:24









                            Redu

                            12.6k22435




                            12.6k22435






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44431043%2fsorting-a-multidimensional-array-in-javascript%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                                Alcedinidae

                                Can an atomic nucleus contain both particles and antiparticles? [duplicate]