find pivot point in javascript

To find pivot point in an array, we need to iterate through the elements of the array and check for each element whether the sum of elements on its left is equal to the sum of elements on its right. If we find such an element, we return its index as the pivot point. Otherwise, we return -1 to indicate that there is no pivot point in the array.

Here is the code to find pivot point in javascript:

index.tsx
function findPivot(arr) {
  let leftSum = 0;
  let rightSum = arr.reduce((acc, val) => acc + val, 0);
  for (let i = 0; i < arr.length; i++) {
    rightSum -= arr[i];
    if (leftSum === rightSum) {
      return i;
    }
    leftSum += arr[i];
  }
  return -1;
}
263 chars
13 lines

We start by initializing leftSum to 0 and rightSum to the sum of all elements in the array using the reduce method. Then we iterate through the array using for loop and for each element, we subtract it from rightSum and check if leftSum is equal to rightSum. If it is, we return the index of that element as the pivot point. Otherwise, we add the element to leftSum and continue the loop. If we reach the end of the loop without finding any pivot point, we return -1.

gistlibby LogSnag