Javascript: Finding the most middle value in an array [closed] Javascript: Finding the most middle value in an array [closed] arrays arrays

Javascript: Finding the most middle value in an array [closed]


If you have an array with for example five items, the middle item is at index two:

var arr = [ item, item, middle, item, item];

Dividing the length by two and using Math.round would give you index three rather than two, so you would need to subtract one from the length first:

var middle = arr[Math.round((arr.length - 1) / 2)];

You say in your question that you are supposed to use Math.round, but if that is not a requirement, you can get the same result easier using Math.floor:

var middle = arr[Math.floor(arr.length / 2)];

For an array with an even number of items, that will give you the second of the two items that are in the middle. If you want the first instead, use Math.floor and substract one from the length. That still gives the same result for odd number of items:

var middle = arr[Math.floor((arr.length - 1) / 2)];


Get the index in the middle of the Array:

var arr = [0, 0, 1, 0, 0];var theMiddle = Math.floor(arr.length / 2); // index 2var value = arr[theMiddle]; // value 1

One-liner:

var value = arr[arr.length / 2 | 0];


You can try this one too:

function test(arr){        var middle_index = parseInt((arr.length/2).toFixed(), 10) - 1;  if(middle_index === -1)    alert('Array empty');  else    alert('Middle value in array ['+arr+'] is '+arr[middle_index]);}

DEMO Link