Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Okay, so what I need to do is return the most middle value in an array. And I'm supposed to use Math.round to calculate the middle index in the array. Just to be clear, I'm NOT talking about the median, just the middle value.

That's what I need to do in text, since I'm new at javascript I don't however know how to quite execute this. Any ideas?

Also, if you think,this question doesn't belong here or is stupid, please direct me to somewhere where I can find this information, I'm just trying to learn here.

function test(arr) {   } 
like image 235
Andrew P Avatar asked Jan 03 '14 13:01

Andrew P


People also ask

How do you find the middle value of an array?

If the array length is even then median will be arr[(arr. length)/2] +arr[((arr. length)/2)+1]. If the array length is odd then the median will be a middle element.

How can you find middle element of an array without using length?

one way you can find midpoint of array is (for odd length array) just use two loops ,1st loop start traverse from 0 index and the other (nested) loop will traverse from last index of array. Now just compare elements when it comes same ...that will be the mid point of array. i.e if(arr[i]== arr[j]) .


1 Answers

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)]; 
like image 83
Guffa Avatar answered Oct 19 '22 14:10

Guffa