JS: Balanced Index

Given an array of numbers, find the index where the sums are balanced to the left and right of it.

const balancedIndex = (array) => {
}

ex — 
input: [1, 2, 5, 3]
output: 2 — to the right of index 2 is 3 and to the left of index 2 is 1 and 2 (equates to 3). If theres is no balanced index, our output will be -1

What to keep in mind? A few questions I asked myself before tackling this problem. How will I achieve the total sum to the right of my index? Totaling all of the numbers in the inputted array first will help me achieve this— following that, I will loop through the array and subtract the values of each iteration against the total.

const balancedIndex = (array) => {
let total = array.reduce((a,b) => a + b);
  for (let i = 0; i < array.length; i++) {
// subtract the total with the current value of array[i]
total = total - array[i];
}
// if there is no balanced index, return -1
return -1;
};
balancedIndex([1, 2, 5, 3]);

Each iteration will look like this:
i : total
0 : 10
1 : 8
2 : 3
3 : 0

How can I successfully compare the sum of the left of the index against the right? During each iteration, I will keep track of the sum to the left.

const balancedIndex = (array) => {
let total = array.reduce((a,b) => a + b);
let sumLeft = 0;

for (let i = 0; i < array.length; i++) {
total = total - array[i];
//compares the sum to the left of current index against total
if (sumLeft === total) {
// if the sums match, the current index will be returned
return i;
}
sumLeft += array[i];
}
return -1;
};
balancedIndex([1, 2, 5, 3]); 
// output: 2

Each iteration will look like this:
i : total : sumLeft
0 : 10 : 1
1 : 8 : 3
2 : 3

The total and sumLeft is being checked before sumLeft += array[i] is ran because the numbers to the right of the index needs to subtract the value of the current index for an accurate comparison.

Like what you read? Give Sara Gee a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.