Computer >> Computer tutorials >  >> Programming >> Javascript

Finding median index of array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array, arr, that represents the positions of different asteroids in a one-dimensional space.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Our function is supposed to find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

For example, if the input to the function is −

Input

const arr = [1, 7, 3, 6, 5, 6];

Output

const output = 3;

Output Explanation

The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.

Also, 3 is the first index where this occurs.

Example

Following is the code −

const arr = [1, 7, 3, 6, 5, 6];
const medianIndex = (arr = []) => {
   let sum = arr.reduce((acc, num) => acc + num, 0)
   let currentSum = 0
   for (let i = 0; i < arr.length; i++) {
      currentSum += (arr[i - 1] || 0)
      sum -= arr[i]
      if (currentSum === sum) {
         return i
      }
   }
   return -1
}
console.log(medianIndex(arr));

Output

3