I am trying to do this challenge where the function should return the index value of the element when the sum of the values on either side of the element are equal. E.g. [1,2,3,4,3,2,1] should return 3, since on the other sides of '4' the values add to 6 (1+2+3) and (3+2+1). Also if there is no such value then the function should return -1.
function findEvenIndex(arr) {
arr.forEach((element, index) => {
let a = arr.splice(index + 1, arr.length); //array of values after current value
let b = arr.splice(arr[0], index); //array of values before current value
let suma = a.reduce((accumulator, currentValue) => { //Sum of array of after values
return accumulator + currentValue;
}, 0);
let sumb = b.reduce((accumulator, currentValue) => { //Sum of array of before values
return accumulator + currentValue;
}, 0);
if (suma === sumb) { //comparing the two sums to check if they are equal
return index;
};
});
};
My understanding was that if suma and sumb are NOT equal, then the next iteration of the forLoop will begin, however this does not happen and I cannot see why.
The function should return -1 if no such value exists, I haven't implemented this part of the code currently.
Thanks