0

Print only negative nums its sum applying loop 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: (", "). https://code.sololearn.com/W1amtvybr5d2/?ref=app

30th Nov 2019, 10:37 PM
Jorge Muñoz
Jorge Muñoz - avatar
5 Antworten
0
I deleted my original comment as I had missed something, but this works:- function negativeArray(array) { document.write("Negative integers: ") var myarr = []; for (var i = 0, count = 0; i < array.length; i++) { if (array[i] != undefined && array[i] < 0){ myarr.push(array[i]); count += array[i]; } } document.write( "<br>The negative nums: " + myarr); document.write( "<br>Sum negative nums: " + count); } var items = [1, -2, 3, 4- 5, 6, -7, -8]; negativeArray(items);
30th Nov 2019, 11:35 PM
rodwynnejones
rodwynnejones - avatar
+ 3
rodwynnejones Yes array.push is good idea.
30th Nov 2019, 11:45 PM
A͢J
A͢J - avatar
+ 2
Jorge Muñoz This condition (i != array.length-1) will not work in this result because your main array size is 7 and if you check this condition like this suppose 1 != 6 -2 and comma will add 3 != 6 -1 and comma will add 5 != 6 -7 and comma will add So final array is [-2, -1, -7, ]
30th Nov 2019, 11:09 PM
A͢J
A͢J - avatar
+ 1
rodwynnejones not weird. It's 4 -5. So it's coming -1. I also was wonder first time.
30th Nov 2019, 10:58 PM
A͢J
A͢J - avatar
0
As far as i can see, just remove the if (i != array.length-1) document.write(", "). I commented out (the above code)...ran it and got the output I was expecting...I must be missing something. edit.... weird. it's not picking up the -5. edit again.... ahhh....your missing a comma after the 4.
30th Nov 2019, 10:53 PM
rodwynnejones
rodwynnejones - avatar