Anybody help me to solve this problem that how to sum up the elements o an array from left to right?

50 Views Asked by At

My challenge is to find an element of the array such that the sum of all elements to the left is equal to the sum of all elements to the right. Example arr=[5,6,8,11] 8 is between two subarrays that sum to 11.

function balancedSums(arr) {

}

balancedSums([1,2,3,3])

1

There are 1 best solutions below

0
nem0z On

I think the function below do the job, it returns the index of the element you are looking for :

const sum = arr => arr.reduce((ps, a) => ps + a, 0);

let balancedSums = function(arr) {
    for(const i in arr) {
        if(sum(arr.slice(0, i)) === sum(arr.slice(parseInt(i) + 1, arr.length))) return i;
    }
    return -1;
};

let arr = [5, 6, 8, 11];
let result = balancedSums(arr);
console.log(`${result} => ${arr[result]}`);

If you have any question about this code, you can ask me in comments ;)