Test whether all array elements are factors of a number The 2019 Stack Overflow Developer Survey Results Are InSearching array reports “not found” even though it's foundPHP: Delete an element from an arrayDeleting array elements in JavaScript - delete vs spliceWhy is setTimeout(fn, 0) sometimes useful?How do I determine whether an array contains a particular value in Java?Determine whether an array contains a valueGet the first element of an arrayGet all unique values in a JavaScript array (remove duplicates)How do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?How does PHP 'foreach' actually work?

A poker game description that does not feel gimmicky

Where to refill my bottle in India?

What does "sndry explns" mean in one of the Hitchhiker's guide books?

What is the use of option -o in the useradd command?

In microwave frequencies, do you use a circulator when you need a (near) perfect diode?

How long do I have to send my income tax payment to the IRS?

Realistic Alternatives to Dust: What Else Could Feed a Plankton Bloom?

If the Wish spell is used to duplicate the effect of Simulacrum, are existing duplicates destroyed?

How to make payment on the internet without leaving a money trail?

Adding labels to a table: columns and rows

Could JWST stay at L2 "forever"?

Output the Arecibo Message

What does "rabbited" mean/imply in this sentence?

How to change the limits of integration

Idiomatic way to prevent slicing?

Spanish for "widget"

Access elements in std::string where positon of string is greater than its size

How do you say "canon" as in "official for a story universe"?

aging parents with no investments

What does Linus Torvalds mean when he says that Git "never ever" tracks a file?

What do hard-Brexiteers want with respect to the Irish border?

Flying Bloodthirsty Lampshades

Extreme, unacceptable situation and I can't attend work tomorrow morning

Which Sci-Fi work first showed weapon of galactic-scale mass destruction?



Test whether all array elements are factors of a number



The 2019 Stack Overflow Developer Survey Results Are InSearching array reports “not found” even though it's foundPHP: Delete an element from an arrayDeleting array elements in JavaScript - delete vs spliceWhy is setTimeout(fn, 0) sometimes useful?How do I determine whether an array contains a particular value in Java?Determine whether an array contains a valueGet the first element of an arrayGet all unique values in a JavaScript array (remove duplicates)How do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?How does PHP 'foreach' actually work?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I have the following question:




Write a function that returns true if all integers in an array are factors of a number, and false otherwise.




I tried the code below:






function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false





My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.










share|improve this question



















  • 2





    You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

    – Icepickle
    Apr 6 at 13:07







  • 2





    FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

    – T.J. Crowder
    Apr 6 at 13:09






  • 1





    @t.j.crowder yet we don't have a good dupetarget for it.

    – Jonas Wilms
    Apr 6 at 13:14






  • 2





    @JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

    – T.J. Crowder
    Apr 6 at 13:18











  • @T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

    – Barmar
    Apr 6 at 18:43


















7















I have the following question:




Write a function that returns true if all integers in an array are factors of a number, and false otherwise.




I tried the code below:






function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false





My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.










share|improve this question



















  • 2





    You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

    – Icepickle
    Apr 6 at 13:07







  • 2





    FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

    – T.J. Crowder
    Apr 6 at 13:09






  • 1





    @t.j.crowder yet we don't have a good dupetarget for it.

    – Jonas Wilms
    Apr 6 at 13:14






  • 2





    @JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

    – T.J. Crowder
    Apr 6 at 13:18











  • @T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

    – Barmar
    Apr 6 at 18:43














7












7








7


1






I have the following question:




Write a function that returns true if all integers in an array are factors of a number, and false otherwise.




I tried the code below:






function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false





My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.










share|improve this question
















I have the following question:




Write a function that returns true if all integers in an array are factors of a number, and false otherwise.




I tried the code below:






function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false





My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.






function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false





function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
console.log(element)

if (num % element !== 0)
return false

else
return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false






javascript arrays loops if-statement






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 6 at 16:50









isanae

2,55711437




2,55711437










asked Apr 6 at 13:04









PineNuts0PineNuts0

87631432




87631432







  • 2





    You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

    – Icepickle
    Apr 6 at 13:07







  • 2





    FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

    – T.J. Crowder
    Apr 6 at 13:09






  • 1





    @t.j.crowder yet we don't have a good dupetarget for it.

    – Jonas Wilms
    Apr 6 at 13:14






  • 2





    @JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

    – T.J. Crowder
    Apr 6 at 13:18











  • @T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

    – Barmar
    Apr 6 at 18:43













  • 2





    You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

    – Icepickle
    Apr 6 at 13:07







  • 2





    FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

    – T.J. Crowder
    Apr 6 at 13:09






  • 1





    @t.j.crowder yet we don't have a good dupetarget for it.

    – Jonas Wilms
    Apr 6 at 13:14






  • 2





    @JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

    – T.J. Crowder
    Apr 6 at 13:18











  • @T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

    – Barmar
    Apr 6 at 18:43








2




2





You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

– Icepickle
Apr 6 at 13:07






You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument

– Icepickle
Apr 6 at 13:07





2




2





FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

– T.J. Crowder
Apr 6 at 13:09





FYI, it's not just you, this is one of the most common errors people make when they first start out with programming and loops. :-)

– T.J. Crowder
Apr 6 at 13:09




1




1





@t.j.crowder yet we don't have a good dupetarget for it.

– Jonas Wilms
Apr 6 at 13:14





@t.j.crowder yet we don't have a good dupetarget for it.

– Jonas Wilms
Apr 6 at 13:14




2




2





@JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

– T.J. Crowder
Apr 6 at 13:18





@JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-)

– T.J. Crowder
Apr 6 at 13:18













@T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

– Barmar
Apr 6 at 18:43






@T.J.Crowder stackoverflow.com/questions/42913798/… is the general dupe I wrote for this class of problems.

– Barmar
Apr 6 at 18:43













5 Answers
5






active

oldest

votes


















5














Just place return true out of for loop,



If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number




Let's understand by 1st example




  • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.

  • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true




function checkFactors(factors, num) 

for (let i=0; i<factors.length; i++)
let element = factors[i];
if (num % element !== 0)
return false


return true




console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
console.log(checkFactors([1, 2], 2))






In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like




  1. keep the failing case return value inside for loop

  2. keep the passing case return value at the end of function

JS have a inbuilt method Array.every for such cases






function checkFactors(factors, num) 
return factors.every(element => num % element === 0);

console.log(checkFactors([1, 2, 3, 8], 12));
console.log(checkFactors([1, 2], 2));








share|improve this answer
































    7














    You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:



    Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹



    You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.



    You realize that your boss actually wanted you to do:



    Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²



    Or in code:



     // ¹
    function checkChocolates(chocolates)
    for(const chocolate of chocolates)
    if(isTasty(chocolate))
    return true;
    else
    return false;




    // ²
    function checkChocolates(chocolates)
    for(const chocolate of chocolates)
    if(isTasty(chocolate))
    continue; // this could be omitted, as a loop keeps looping nevertheless
    else
    return false;


    return true;



    As this is a very common task in programming, there is already a shorter way to express this:



     if(chocolates.every(isTasty)) 
    alert("all chocolates are fine");
    else
    alert("Oh, that doesnt taste good");



    whereas isTasty is a function taking a chocolate and returning either true or false.




    If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)






    share|improve this answer




















    • 1





      A tiny quibble - it's "chocolate", not "choclate".

      – Wai Ha Lee
      Apr 6 at 13:25






    • 1





      @waiHaLee oh, pronounciation tricked me ...

      – Jonas Wilms
      Apr 6 at 13:28


















    1














    Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.



    The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.



    Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.






    function checkFactors(factors, num) 
    let flag = true;
    for (let i=0; i<factors.length; i++)
    let element = factors[i];
    if (num % element !== 0)
    flag = false;
    break;


    return flag;


    console.log(checkFactors([1, 2, 3, 8], 12));
    console.log(checkFactors([1, 2], 2));
    console.log(checkFactors([2, 4, 3, 6, 9], 12));
    console.log(checkFactors([3, 5, 2, 6, 9], 15));
    console.log(checkFactors([4, 2, 8, 1], 16));





    You can also use Array.every to check the same in a concise way:






    function checkFactors(factors, num) 
    return factors.every(element => num % element === 0);

    console.log(checkFactors([1, 2, 3, 8], 12));
    console.log(checkFactors([1, 2], 2));
    console.log(checkFactors([2, 4, 3, 6, 9], 12));
    console.log(checkFactors([3, 5, 2, 6, 9], 15));
    console.log(checkFactors([4, 2, 8, 1], 16));








    share|improve this answer
































      0














      Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.



      function checkFactors(factors, num) 

      for (let i=0; i<factors.length; i++)
      let element = factors[i];
      console.log(element)

      if (num % element !== 0)
      return false


      return true;






      share|improve this answer


















      • 1





        He is looking for an explanation as well though

        – Icepickle
        Apr 6 at 13:10











      • I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

        – javapedia.net
        Apr 6 at 13:12



















      0














      Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.






      share|improve this answer








      New contributor




      W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















        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%2f55549338%2ftest-whether-all-array-elements-are-factors-of-a-number%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        5














        Just place return true out of for loop,



        If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number




        Let's understand by 1st example




        • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.

        • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true




        function checkFactors(factors, num) 

        for (let i=0; i<factors.length; i++)
        let element = factors[i];
        if (num % element !== 0)
        return false


        return true




        console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
        console.log(checkFactors([1, 2], 2))






        In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like




        1. keep the failing case return value inside for loop

        2. keep the passing case return value at the end of function

        JS have a inbuilt method Array.every for such cases






        function checkFactors(factors, num) 
        return factors.every(element => num % element === 0);

        console.log(checkFactors([1, 2, 3, 8], 12));
        console.log(checkFactors([1, 2], 2));








        share|improve this answer





























          5














          Just place return true out of for loop,



          If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number




          Let's understand by 1st example




          • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.

          • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true




          function checkFactors(factors, num) 

          for (let i=0; i<factors.length; i++)
          let element = factors[i];
          if (num % element !== 0)
          return false


          return true




          console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
          console.log(checkFactors([1, 2], 2))






          In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like




          1. keep the failing case return value inside for loop

          2. keep the passing case return value at the end of function

          JS have a inbuilt method Array.every for such cases






          function checkFactors(factors, num) 
          return factors.every(element => num % element === 0);

          console.log(checkFactors([1, 2, 3, 8], 12));
          console.log(checkFactors([1, 2], 2));








          share|improve this answer



























            5












            5








            5







            Just place return true out of for loop,



            If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number




            Let's understand by 1st example




            • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.

            • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true




            function checkFactors(factors, num) 

            for (let i=0; i<factors.length; i++)
            let element = factors[i];
            if (num % element !== 0)
            return false


            return true




            console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
            console.log(checkFactors([1, 2], 2))






            In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like




            1. keep the failing case return value inside for loop

            2. keep the passing case return value at the end of function

            JS have a inbuilt method Array.every for such cases






            function checkFactors(factors, num) 
            return factors.every(element => num % element === 0);

            console.log(checkFactors([1, 2, 3, 8], 12));
            console.log(checkFactors([1, 2], 2));








            share|improve this answer















            Just place return true out of for loop,



            If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number




            Let's understand by 1st example




            • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.

            • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true




            function checkFactors(factors, num) 

            for (let i=0; i<factors.length; i++)
            let element = factors[i];
            if (num % element !== 0)
            return false


            return true




            console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
            console.log(checkFactors([1, 2], 2))






            In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like




            1. keep the failing case return value inside for loop

            2. keep the passing case return value at the end of function

            JS have a inbuilt method Array.every for such cases






            function checkFactors(factors, num) 
            return factors.every(element => num % element === 0);

            console.log(checkFactors([1, 2, 3, 8], 12));
            console.log(checkFactors([1, 2], 2));








            function checkFactors(factors, num) 

            for (let i=0; i<factors.length; i++)
            let element = factors[i];
            if (num % element !== 0)
            return false


            return true




            console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
            console.log(checkFactors([1, 2], 2))





            function checkFactors(factors, num) 

            for (let i=0; i<factors.length; i++)
            let element = factors[i];
            if (num % element !== 0)
            return false


            return true




            console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
            console.log(checkFactors([1, 2], 2))





            function checkFactors(factors, num) 
            return factors.every(element => num % element === 0);

            console.log(checkFactors([1, 2, 3, 8], 12));
            console.log(checkFactors([1, 2], 2));





            function checkFactors(factors, num) 
            return factors.every(element => num % element === 0);

            console.log(checkFactors([1, 2, 3, 8], 12));
            console.log(checkFactors([1, 2], 2));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 6 at 16:22

























            answered Apr 6 at 13:07









            Code ManiacCode Maniac

            11.8k2834




            11.8k2834























                7














                You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:



                Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹



                You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.



                You realize that your boss actually wanted you to do:



                Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²



                Or in code:



                 // ¹
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                return true;
                else
                return false;




                // ²
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                continue; // this could be omitted, as a loop keeps looping nevertheless
                else
                return false;


                return true;



                As this is a very common task in programming, there is already a shorter way to express this:



                 if(chocolates.every(isTasty)) 
                alert("all chocolates are fine");
                else
                alert("Oh, that doesnt taste good");



                whereas isTasty is a function taking a chocolate and returning either true or false.




                If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)






                share|improve this answer




















                • 1





                  A tiny quibble - it's "chocolate", not "choclate".

                  – Wai Ha Lee
                  Apr 6 at 13:25






                • 1





                  @waiHaLee oh, pronounciation tricked me ...

                  – Jonas Wilms
                  Apr 6 at 13:28















                7














                You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:



                Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹



                You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.



                You realize that your boss actually wanted you to do:



                Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²



                Or in code:



                 // ¹
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                return true;
                else
                return false;




                // ²
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                continue; // this could be omitted, as a loop keeps looping nevertheless
                else
                return false;


                return true;



                As this is a very common task in programming, there is already a shorter way to express this:



                 if(chocolates.every(isTasty)) 
                alert("all chocolates are fine");
                else
                alert("Oh, that doesnt taste good");



                whereas isTasty is a function taking a chocolate and returning either true or false.




                If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)






                share|improve this answer




















                • 1





                  A tiny quibble - it's "chocolate", not "choclate".

                  – Wai Ha Lee
                  Apr 6 at 13:25






                • 1





                  @waiHaLee oh, pronounciation tricked me ...

                  – Jonas Wilms
                  Apr 6 at 13:28













                7












                7








                7







                You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:



                Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹



                You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.



                You realize that your boss actually wanted you to do:



                Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²



                Or in code:



                 // ¹
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                return true;
                else
                return false;




                // ²
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                continue; // this could be omitted, as a loop keeps looping nevertheless
                else
                return false;


                return true;



                As this is a very common task in programming, there is already a shorter way to express this:



                 if(chocolates.every(isTasty)) 
                alert("all chocolates are fine");
                else
                alert("Oh, that doesnt taste good");



                whereas isTasty is a function taking a chocolate and returning either true or false.




                If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)






                share|improve this answer















                You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:



                Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹



                You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.



                You realize that your boss actually wanted you to do:



                Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²



                Or in code:



                 // ¹
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                return true;
                else
                return false;




                // ²
                function checkChocolates(chocolates)
                for(const chocolate of chocolates)
                if(isTasty(chocolate))
                continue; // this could be omitted, as a loop keeps looping nevertheless
                else
                return false;


                return true;



                As this is a very common task in programming, there is already a shorter way to express this:



                 if(chocolates.every(isTasty)) 
                alert("all chocolates are fine");
                else
                alert("Oh, that doesnt taste good");



                whereas isTasty is a function taking a chocolate and returning either true or false.




                If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 6 at 13:31

























                answered Apr 6 at 13:10









                Jonas WilmsJonas Wilms

                65.6k53660




                65.6k53660







                • 1





                  A tiny quibble - it's "chocolate", not "choclate".

                  – Wai Ha Lee
                  Apr 6 at 13:25






                • 1





                  @waiHaLee oh, pronounciation tricked me ...

                  – Jonas Wilms
                  Apr 6 at 13:28












                • 1





                  A tiny quibble - it's "chocolate", not "choclate".

                  – Wai Ha Lee
                  Apr 6 at 13:25






                • 1





                  @waiHaLee oh, pronounciation tricked me ...

                  – Jonas Wilms
                  Apr 6 at 13:28







                1




                1





                A tiny quibble - it's "chocolate", not "choclate".

                – Wai Ha Lee
                Apr 6 at 13:25





                A tiny quibble - it's "chocolate", not "choclate".

                – Wai Ha Lee
                Apr 6 at 13:25




                1




                1





                @waiHaLee oh, pronounciation tricked me ...

                – Jonas Wilms
                Apr 6 at 13:28





                @waiHaLee oh, pronounciation tricked me ...

                – Jonas Wilms
                Apr 6 at 13:28











                1














                Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.



                The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.



                Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.






                function checkFactors(factors, num) 
                let flag = true;
                for (let i=0; i<factors.length; i++)
                let element = factors[i];
                if (num % element !== 0)
                flag = false;
                break;


                return flag;


                console.log(checkFactors([1, 2, 3, 8], 12));
                console.log(checkFactors([1, 2], 2));
                console.log(checkFactors([2, 4, 3, 6, 9], 12));
                console.log(checkFactors([3, 5, 2, 6, 9], 15));
                console.log(checkFactors([4, 2, 8, 1], 16));





                You can also use Array.every to check the same in a concise way:






                function checkFactors(factors, num) 
                return factors.every(element => num % element === 0);

                console.log(checkFactors([1, 2, 3, 8], 12));
                console.log(checkFactors([1, 2], 2));
                console.log(checkFactors([2, 4, 3, 6, 9], 12));
                console.log(checkFactors([3, 5, 2, 6, 9], 15));
                console.log(checkFactors([4, 2, 8, 1], 16));








                share|improve this answer





























                  1














                  Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.



                  The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.



                  Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.






                  function checkFactors(factors, num) 
                  let flag = true;
                  for (let i=0; i<factors.length; i++)
                  let element = factors[i];
                  if (num % element !== 0)
                  flag = false;
                  break;


                  return flag;


                  console.log(checkFactors([1, 2, 3, 8], 12));
                  console.log(checkFactors([1, 2], 2));
                  console.log(checkFactors([2, 4, 3, 6, 9], 12));
                  console.log(checkFactors([3, 5, 2, 6, 9], 15));
                  console.log(checkFactors([4, 2, 8, 1], 16));





                  You can also use Array.every to check the same in a concise way:






                  function checkFactors(factors, num) 
                  return factors.every(element => num % element === 0);

                  console.log(checkFactors([1, 2, 3, 8], 12));
                  console.log(checkFactors([1, 2], 2));
                  console.log(checkFactors([2, 4, 3, 6, 9], 12));
                  console.log(checkFactors([3, 5, 2, 6, 9], 15));
                  console.log(checkFactors([4, 2, 8, 1], 16));








                  share|improve this answer



























                    1












                    1








                    1







                    Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.



                    The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.



                    Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.






                    function checkFactors(factors, num) 
                    let flag = true;
                    for (let i=0; i<factors.length; i++)
                    let element = factors[i];
                    if (num % element !== 0)
                    flag = false;
                    break;


                    return flag;


                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));





                    You can also use Array.every to check the same in a concise way:






                    function checkFactors(factors, num) 
                    return factors.every(element => num % element === 0);

                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));








                    share|improve this answer















                    Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.



                    The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.



                    Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.






                    function checkFactors(factors, num) 
                    let flag = true;
                    for (let i=0; i<factors.length; i++)
                    let element = factors[i];
                    if (num % element !== 0)
                    flag = false;
                    break;


                    return flag;


                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));





                    You can also use Array.every to check the same in a concise way:






                    function checkFactors(factors, num) 
                    return factors.every(element => num % element === 0);

                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));








                    function checkFactors(factors, num) 
                    let flag = true;
                    for (let i=0; i<factors.length; i++)
                    let element = factors[i];
                    if (num % element !== 0)
                    flag = false;
                    break;


                    return flag;


                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));





                    function checkFactors(factors, num) 
                    let flag = true;
                    for (let i=0; i<factors.length; i++)
                    let element = factors[i];
                    if (num % element !== 0)
                    flag = false;
                    break;


                    return flag;


                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));





                    function checkFactors(factors, num) 
                    return factors.every(element => num % element === 0);

                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));





                    function checkFactors(factors, num) 
                    return factors.every(element => num % element === 0);

                    console.log(checkFactors([1, 2, 3, 8], 12));
                    console.log(checkFactors([1, 2], 2));
                    console.log(checkFactors([2, 4, 3, 6, 9], 12));
                    console.log(checkFactors([3, 5, 2, 6, 9], 15));
                    console.log(checkFactors([4, 2, 8, 1], 16));






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 6 at 13:29

























                    answered Apr 6 at 13:12









                    Amardeep BhowmickAmardeep Bhowmick

                    5,59821128




                    5,59821128





















                        0














                        Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.



                        function checkFactors(factors, num) 

                        for (let i=0; i<factors.length; i++)
                        let element = factors[i];
                        console.log(element)

                        if (num % element !== 0)
                        return false


                        return true;






                        share|improve this answer


















                        • 1





                          He is looking for an explanation as well though

                          – Icepickle
                          Apr 6 at 13:10











                        • I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                          – javapedia.net
                          Apr 6 at 13:12
















                        0














                        Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.



                        function checkFactors(factors, num) 

                        for (let i=0; i<factors.length; i++)
                        let element = factors[i];
                        console.log(element)

                        if (num % element !== 0)
                        return false


                        return true;






                        share|improve this answer


















                        • 1





                          He is looking for an explanation as well though

                          – Icepickle
                          Apr 6 at 13:10











                        • I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                          – javapedia.net
                          Apr 6 at 13:12














                        0












                        0








                        0







                        Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.



                        function checkFactors(factors, num) 

                        for (let i=0; i<factors.length; i++)
                        let element = factors[i];
                        console.log(element)

                        if (num % element !== 0)
                        return false


                        return true;






                        share|improve this answer













                        Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.



                        function checkFactors(factors, num) 

                        for (let i=0; i<factors.length; i++)
                        let element = factors[i];
                        console.log(element)

                        if (num % element !== 0)
                        return false


                        return true;







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Apr 6 at 13:08









                        javapedia.netjavapedia.net

                        575312




                        575312







                        • 1





                          He is looking for an explanation as well though

                          – Icepickle
                          Apr 6 at 13:10











                        • I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                          – javapedia.net
                          Apr 6 at 13:12













                        • 1





                          He is looking for an explanation as well though

                          – Icepickle
                          Apr 6 at 13:10











                        • I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                          – javapedia.net
                          Apr 6 at 13:12








                        1




                        1





                        He is looking for an explanation as well though

                        – Icepickle
                        Apr 6 at 13:10





                        He is looking for an explanation as well though

                        – Icepickle
                        Apr 6 at 13:10













                        I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                        – javapedia.net
                        Apr 6 at 13:12






                        I see Icepickle has explained in the question comments nicely! Jonas Wilms's answer too.

                        – javapedia.net
                        Apr 6 at 13:12












                        0














                        Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.






                        share|improve this answer








                        New contributor




                        W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.
























                          0














                          Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.






                          share|improve this answer








                          New contributor




                          W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






















                            0












                            0








                            0







                            Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.






                            share|improve this answer








                            New contributor




                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.










                            Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.







                            share|improve this answer








                            New contributor




                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.









                            share|improve this answer



                            share|improve this answer






                            New contributor




                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.









                            answered Apr 6 at 13:26









                            W.BrightW.Bright

                            133




                            133




                            New contributor




                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.





                            New contributor





                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






                            W.Bright is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.



























                                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%2f55549338%2ftest-whether-all-array-elements-are-factors-of-a-number%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

                                getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

                                Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

                                Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.