- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Finding median for every window in JavaScript
- Finding the index position of an array inside an array JavaScript
- Calculating median of an array JavaScript
- Calculating median of an array in JavaScript
- Finding reversed index of elements in arrays - JavaScript
- Finding the nth power of array element present at nth index using JavaScript
- Median of two sorted array
- Finding the index of last element in the array in C#
- Finding the index of first element in the array in C#
- Finding special array - JavaScript
- Finding quarter based on month index in JavaScript
- Finding Mean, Median, Mode in Python without Libraries
- Find closest index of array in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript