Multiply nested array lengths and return a single valueHow do I determine whether an array contains a particular value in Java?Sort array of objects by string property valueDetermine whether an array contains a valueGet all unique values in a JavaScript array (remove duplicates)Check if a value exists in an array in RubyHow to Sort Multi-dimensional Array by Value?How to remove item from array by value?Copy array by valueRemove duplicate values from JS arrayAccess / process (nested) objects, arrays or JSON

Valid Badminton Score?

What is the term when two people sing in harmony, but they aren't singing the same notes?

What is the oldest known work of fiction?

What will be the benefits of Brexit?

apt-get update is failing in debian

Can somebody explain Brexit in a few child-proof sentences?

Time travel short story where a man arrives in the late 19th century in a time machine and then sends the machine back into the past

Is HostGator storing my password in plaintext?

Your magic is very sketchy

Why "be dealt cards" rather than "be dealing cards"?

voltage of sounds of mp3files

What is the opposite of 'gravitas'?

What would happen if the UK refused to take part in EU Parliamentary elections?

Ways to speed up user implemented RK4

Can criminal fraud exist without damages?

How was Earth single-handedly capable of creating 3 of the 4 gods of chaos?

Print name if parameter passed to function

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

Trouble understanding overseas colleagues

What are the ramifications of creating a homebrew world without an Astral Plane?

How to be diplomatic in refusing to write code that breaches the privacy of our users

What is difference between behavior and behaviour

Where in the Bible does the greeting ("Dominus Vobiscum") used at Mass come from?

Can I use my Chinese passport to enter China after I acquired another citizenship?



Multiply nested array lengths and return a single value


How do I determine whether an array contains a particular value in Java?Sort array of objects by string property valueDetermine whether an array contains a valueGet all unique values in a JavaScript array (remove duplicates)Check if a value exists in an array in RubyHow to Sort Multi-dimensional Array by Value?How to remove item from array by value?Copy array by valueRemove duplicate values from JS arrayAccess / process (nested) objects, arrays or JSON













0















How can i multiply the length of the nested values array using this array:



const options = [

name: "Colors",
values: [
label: "Blue"
,

label: "Red"
]
,

name: "Sizes",
values: [
label: "Small"
,

label: "Large"
]

]



My code:






const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);





I've tried with reduce but always return 0. It should return ex. 4



playground: https://codesandbox.io/s/08jrnr72w



edit: thanks everyone for the answers, I missed initial position...










share|improve this question



















  • 2





    You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

    – briosheje
    Mar 7 at 11:38
















0















How can i multiply the length of the nested values array using this array:



const options = [

name: "Colors",
values: [
label: "Blue"
,

label: "Red"
]
,

name: "Sizes",
values: [
label: "Small"
,

label: "Large"
]

]



My code:






const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);





I've tried with reduce but always return 0. It should return ex. 4



playground: https://codesandbox.io/s/08jrnr72w



edit: thanks everyone for the answers, I missed initial position...










share|improve this question



















  • 2





    You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

    – briosheje
    Mar 7 at 11:38














0












0








0


1






How can i multiply the length of the nested values array using this array:



const options = [

name: "Colors",
values: [
label: "Blue"
,

label: "Red"
]
,

name: "Sizes",
values: [
label: "Small"
,

label: "Large"
]

]



My code:






const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);





I've tried with reduce but always return 0. It should return ex. 4



playground: https://codesandbox.io/s/08jrnr72w



edit: thanks everyone for the answers, I missed initial position...










share|improve this question
















How can i multiply the length of the nested values array using this array:



const options = [

name: "Colors",
values: [
label: "Blue"
,

label: "Red"
]
,

name: "Sizes",
values: [
label: "Small"
,

label: "Large"
]

]



My code:






const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);





I've tried with reduce but always return 0. It should return ex. 4



playground: https://codesandbox.io/s/08jrnr72w



edit: thanks everyone for the answers, I missed initial position...






const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);





const options = [

name: "Colors",
values: [

label: "Blue"
,

label: "Red"

]
,

name: "Sizes",
values: [

label: "Small"
,

label: "Large"

]

];

const multiply = options.reduce((a, b) => a * b.values.length, 0);

console.log(multiply);






javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 11:40









Nick Parsons

10.2k2926




10.2k2926










asked Mar 7 at 11:33









Stathis NtonasStathis Ntonas

453920




453920







  • 2





    You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

    – briosheje
    Mar 7 at 11:38













  • 2





    You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

    – briosheje
    Mar 7 at 11:38








2




2





You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

– briosheje
Mar 7 at 11:38






You are multiplying with an initial value of 0. Any number multiplied by 0 will return 0. Just replace 0 with 1 codesandbox.io/s/l9p345r3x7

– briosheje
Mar 7 at 11:38













4 Answers
4






active

oldest

votes


















3














The reduce function expects an initial value. The initial value you provided is 0. If you multiply 0 with anything, you'll get 0.



You should initialize your accumulator with 1. That should fix it.



But you might have to do more, i.e. handle the edge condition. For example, at one point you may get 0 as length for one particular object and in that case, your accumulator will evaluate to 0.






share|improve this answer























  • This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

    – briosheje
    Mar 7 at 11:39











  • thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

    – Stathis Ntonas
    Mar 7 at 11:42






  • 1





    I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

    – Jayendra Sharan
    Mar 7 at 11:48



















2














You need to initialize Array.prototype.reduce with 1 for multiplication (multiplying by zero is always going to end up as zero):



const multiply = options.reduce((a, b) => a * b.values.length, 1);





share|improve this answer






























    1














    Map them to lengths and then reduce the results.






    const options = [

    name: "Colors",
    values: [
    label: "Blue"
    ,

    label: "Red"
    ]
    ,

    name: "Sizes",
    values: [
    label: "Small"
    ,

    label: "Large"
    ]

    ]

    const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
    console.log(multValues)








    share|improve this answer






























      1














      Change your starting value to 1 as 0 times anything is 0 (thus your accumulator (a) will always be 0):






      const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

      // change starting value -------------------------------------/
      const multiply = options.reduce((a, b) => a * b.values.length, 1);

      console.log(multiply);








      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%2f55042807%2fmultiply-nested-array-lengths-and-return-a-single-value%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        The reduce function expects an initial value. The initial value you provided is 0. If you multiply 0 with anything, you'll get 0.



        You should initialize your accumulator with 1. That should fix it.



        But you might have to do more, i.e. handle the edge condition. For example, at one point you may get 0 as length for one particular object and in that case, your accumulator will evaluate to 0.






        share|improve this answer























        • This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

          – briosheje
          Mar 7 at 11:39











        • thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

          – Stathis Ntonas
          Mar 7 at 11:42






        • 1





          I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

          – Jayendra Sharan
          Mar 7 at 11:48
















        3














        The reduce function expects an initial value. The initial value you provided is 0. If you multiply 0 with anything, you'll get 0.



        You should initialize your accumulator with 1. That should fix it.



        But you might have to do more, i.e. handle the edge condition. For example, at one point you may get 0 as length for one particular object and in that case, your accumulator will evaluate to 0.






        share|improve this answer























        • This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

          – briosheje
          Mar 7 at 11:39











        • thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

          – Stathis Ntonas
          Mar 7 at 11:42






        • 1





          I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

          – Jayendra Sharan
          Mar 7 at 11:48














        3












        3








        3







        The reduce function expects an initial value. The initial value you provided is 0. If you multiply 0 with anything, you'll get 0.



        You should initialize your accumulator with 1. That should fix it.



        But you might have to do more, i.e. handle the edge condition. For example, at one point you may get 0 as length for one particular object and in that case, your accumulator will evaluate to 0.






        share|improve this answer













        The reduce function expects an initial value. The initial value you provided is 0. If you multiply 0 with anything, you'll get 0.



        You should initialize your accumulator with 1. That should fix it.



        But you might have to do more, i.e. handle the edge condition. For example, at one point you may get 0 as length for one particular object and in that case, your accumulator will evaluate to 0.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 11:38









        Jayendra SharanJayendra Sharan

        34927




        34927












        • This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

          – briosheje
          Mar 7 at 11:39











        • thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

          – Stathis Ntonas
          Mar 7 at 11:42






        • 1





          I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

          – Jayendra Sharan
          Mar 7 at 11:48


















        • This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

          – briosheje
          Mar 7 at 11:39











        • thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

          – Stathis Ntonas
          Mar 7 at 11:42






        • 1





          I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

          – Jayendra Sharan
          Mar 7 at 11:48

















        This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

        – briosheje
        Mar 7 at 11:39





        This is the correct answer, since it also takes care of mentioning that there might be an element with 0 length in the array. Moreover, you may also take care of elements that do not have a values property.

        – briosheje
        Mar 7 at 11:39













        thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

        – Stathis Ntonas
        Mar 7 at 11:42





        thanks for pointing it out, in my case values will always have values, @jayendra-sharan would you mind posting an edge condition? It would be great for reference.

        – Stathis Ntonas
        Mar 7 at 11:42




        1




        1





        I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

        – Jayendra Sharan
        Mar 7 at 11:48






        I have created a fork, you can play around it and let me know if something doesn't work. codesandbox.io/s/zx90ww42rl Please mark as accepted if it resolved your issue.

        – Jayendra Sharan
        Mar 7 at 11:48














        2














        You need to initialize Array.prototype.reduce with 1 for multiplication (multiplying by zero is always going to end up as zero):



        const multiply = options.reduce((a, b) => a * b.values.length, 1);





        share|improve this answer



























          2














          You need to initialize Array.prototype.reduce with 1 for multiplication (multiplying by zero is always going to end up as zero):



          const multiply = options.reduce((a, b) => a * b.values.length, 1);





          share|improve this answer

























            2












            2








            2







            You need to initialize Array.prototype.reduce with 1 for multiplication (multiplying by zero is always going to end up as zero):



            const multiply = options.reduce((a, b) => a * b.values.length, 1);





            share|improve this answer













            You need to initialize Array.prototype.reduce with 1 for multiplication (multiplying by zero is always going to end up as zero):



            const multiply = options.reduce((a, b) => a * b.values.length, 1);






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 7 at 11:38









            Rob_MRob_M

            11016




            11016





















                1














                Map them to lengths and then reduce the results.






                const options = [

                name: "Colors",
                values: [
                label: "Blue"
                ,

                label: "Red"
                ]
                ,

                name: "Sizes",
                values: [
                label: "Small"
                ,

                label: "Large"
                ]

                ]

                const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                console.log(multValues)








                share|improve this answer



























                  1














                  Map them to lengths and then reduce the results.






                  const options = [

                  name: "Colors",
                  values: [
                  label: "Blue"
                  ,

                  label: "Red"
                  ]
                  ,

                  name: "Sizes",
                  values: [
                  label: "Small"
                  ,

                  label: "Large"
                  ]

                  ]

                  const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                  console.log(multValues)








                  share|improve this answer

























                    1












                    1








                    1







                    Map them to lengths and then reduce the results.






                    const options = [

                    name: "Colors",
                    values: [
                    label: "Blue"
                    ,

                    label: "Red"
                    ]
                    ,

                    name: "Sizes",
                    values: [
                    label: "Small"
                    ,

                    label: "Large"
                    ]

                    ]

                    const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                    console.log(multValues)








                    share|improve this answer













                    Map them to lengths and then reduce the results.






                    const options = [

                    name: "Colors",
                    values: [
                    label: "Blue"
                    ,

                    label: "Red"
                    ]
                    ,

                    name: "Sizes",
                    values: [
                    label: "Small"
                    ,

                    label: "Large"
                    ]

                    ]

                    const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                    console.log(multValues)








                    const options = [

                    name: "Colors",
                    values: [
                    label: "Blue"
                    ,

                    label: "Red"
                    ]
                    ,

                    name: "Sizes",
                    values: [
                    label: "Small"
                    ,

                    label: "Large"
                    ]

                    ]

                    const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                    console.log(multValues)





                    const options = [

                    name: "Colors",
                    values: [
                    label: "Blue"
                    ,

                    label: "Red"
                    ]
                    ,

                    name: "Sizes",
                    values: [
                    label: "Small"
                    ,

                    label: "Large"
                    ]

                    ]

                    const multValues = options.map(opt => opt.values.length).reduce((a,b) => a*b);
                    console.log(multValues)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 11:36









                    dporechnydporechny

                    50229




                    50229





















                        1














                        Change your starting value to 1 as 0 times anything is 0 (thus your accumulator (a) will always be 0):






                        const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                        // change starting value -------------------------------------/
                        const multiply = options.reduce((a, b) => a * b.values.length, 1);

                        console.log(multiply);








                        share|improve this answer



























                          1














                          Change your starting value to 1 as 0 times anything is 0 (thus your accumulator (a) will always be 0):






                          const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                          // change starting value -------------------------------------/
                          const multiply = options.reduce((a, b) => a * b.values.length, 1);

                          console.log(multiply);








                          share|improve this answer

























                            1












                            1








                            1







                            Change your starting value to 1 as 0 times anything is 0 (thus your accumulator (a) will always be 0):






                            const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                            // change starting value -------------------------------------/
                            const multiply = options.reduce((a, b) => a * b.values.length, 1);

                            console.log(multiply);








                            share|improve this answer













                            Change your starting value to 1 as 0 times anything is 0 (thus your accumulator (a) will always be 0):






                            const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                            // change starting value -------------------------------------/
                            const multiply = options.reduce((a, b) => a * b.values.length, 1);

                            console.log(multiply);








                            const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                            // change starting value -------------------------------------/
                            const multiply = options.reduce((a, b) => a * b.values.length, 1);

                            console.log(multiply);





                            const options=[name:"Colors",values:[label:"Blue",label:"Red"],name:"Sizes",values:[label:"Small",label:"Large"]];

                            // change starting value -------------------------------------/
                            const multiply = options.reduce((a, b) => a * b.values.length, 1);

                            console.log(multiply);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 11:37









                            Nick ParsonsNick Parsons

                            10.2k2926




                            10.2k2926



























                                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.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55042807%2fmultiply-nested-array-lengths-and-return-a-single-value%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

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved