I’m a beginner to Java Script and i had typed out a decent size block of code for a simple arithmetic problem. When my code failed to run i commented parts out to debug it but it still does not run.
Is there a reason why this code returns errors?
function countPositivesSumNegatives(input) {
for (let i = 0; i < input.length; i++){
if (Math.sign(input[i]) == 1 ){
return true;
}
else {
return false;
}
}
}
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative.
If the input is an empty array or is null, return an empty array.
Example
For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].
*/
function countPositivesSumNegatives(input) {
// I started by assigning some accumulators and empty arrays to variables
const sum1 = [];
const sum2 = [];
// Then I created a loop to go through the object "input".
for (let i = 0; i < input.length; i++){
// Nested if statement - "if positive increase count by +1
if (Math.sign(input[i]) == 1 ){
sum1[0] +=1;
}
// else statement to create and array for the negative numbers
else if (Math.sign(input[i]) == -1 ) {
/* First time using splice, not sure i used correctly,
But I want to splice negative number into new array "b"
Which i declared earlier as an empty array*/
sum2.splice(0, 0, input[i]);
// Find sum of spliced elements in array b
const sum2 = sum2.reduce((accumulator, value)=>{
return accumulator + value;
}, 0);
}
}
// Concatenate array sum1 and sum2
return sum1.concat(sum2);
}
If you only used reduce for this having the initial value as an array would make sense.
You need to assign a number to the first element in the sum1 array if you want to use addition on it.
You can not redeclare sum2 for the return of running reduce on sum2. Technically, what happens is you are declaring a new version of sum2 inside the else/if scope and it is used before it is initialized.
// this sum2 is not the one in the outer function scope
// it is the one declared for the return of reduce below
// ReferenceError: Cannot access 'sum2' before initialization
sum2.splice(0, 0, input[i]);
// new sum2 in else/if scope accessed above before initialization
const sum2 = sum2.reduce((accumulator, value) => {
return accumulator + value;
}, 0);
In fact, you can’t declare the variable for the return from reduce using a block scope variable inside that scope (because then you can’t access it outside the scope). It needs to be a variable declared outside the scope using let or inside the scope using var (don’t do the latter).
I agree, I’m not certain why my mind does not automatically gravitate towards the simpler solution. I’ve seen a few other solutions for this question that have me questioning my sanity.