I need to add items to each other from a specific index in array.
function findEvenIndex(arr) {
let leftsum = 0;
let rightsum = 0;
arr.forEach((el, ind) => {
arr.reduce((acc, currv, i) => i > ind + 1 ? acc + currv : 0) //acc = 1 or undefined
leftsum += arr[ind + 1];
rightsum += arr[ind - 1]
})
}
I'd like the accumulator to be equal to ind+1. How should I do it?
How can I predefine the accumulator in Array.prototype.reduce()?
Just supply the second argument to reduce
:
arr.reduce ((acc, currv, i) => i > ind+1 ? acc+currv : 0, ind + 1)
// -------------------------------------------------------^^^^^^^
But it makes no sense to use reduce
if you're not using the return value. That reduce
call is literally a no-op. You're not using the result, and there are no side-effects in the callback.
I asked what this function was meant to do, and you replied in a comment:
I need to take an array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N.
To do that, I'd start as near the middle as possible and then slowly work your way to the edges. Obviously you don't want me to post a solution, but I'd pick the midpoint index, calculate the sum each direction from that index, then for as long as the sums don't match, try moving left one place (subtracting the value at the new index from the left sum and adding it to the right) and check. Then try moving right one place (subtracting the value at the new index from the right sum and adding it to the left) and check. Keep going until you run into the edges.