Search code examples
javascriptarraysfor-loopif-statementnegative-integer

Print only negative numbers and its sum aplaying loops and arrays


I need help with a program, I have to use a loop to output all negative integers and their sum. I should use just basic method.

Negative integers: -2, -1, -7 <----//No comma at the end.

Sum negative nums: -10

When I run my program the last integers has an additional comma at the end, I can’t take it out with “if (i != array.length-1)” because the last element in my array is positive but the loop analyze that there is a empty element. How I can remove that comma in a logical way. The result have to be print inside a loop separate by comma space: (", ").

function negativeArray(array)
    {
        document.write("Negative integers: ")
        for (var i = 0, count = 0; i < array.length; i++) 
        {
            if (array[i] != undefined && array[i] < 0){
                    document.write(array[i]);
                    count += array[i];
                    if (i != array.length-1) document.write(", ")}
        }
            document.write( "<br>Sum negative nums: " + count)
    }
        var items = [1, -2, 3, 4 -5, 6, -7, 8];
        negativeArray(items);


Solution

  • A simpler approach using filter, join and reduce:

    var items = [1, -2, 3, 4 - 5, 6, -7, 8];
    
    document.write(
      "Negative integers: ",
      items.filter(item => item < 0).join(", ")
    );
    
    document.write(
      "<br>Sum negative nums: ",
      items.reduce((acc, current) => acc + (current < 0 ? current : 0), 0)
    );