Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  148] [ 6]  / answers: 1 / hits: 82805  / 11 Years ago, fri, january 3, 2014, 12:00:00

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) {


}

More From » arrays

 Answers
15

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)];

[#73393] Thursday, January 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondd

Total Points: 620
Total Questions: 112
Total Answers: 94

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
raymondd questions
Thu, Apr 22, 21, 00:00, 3 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
Thu, Jul 25, 19, 00:00, 5 Years ago
;