Javascript: finding the most average value in an array

Ok, so what I need to do is return the most average value in the array. And I have to use Math.round to calculate the average index in the array. To be clear, I'm not talking about the median , just the average.

What I need to do in the text, since I am new to javascript, I do not know how to accomplish this. Any ideas?

In addition, if you think this question does not belong here or is stupid, please direct me somewhere where I can find this information, I'm just trying to find out here.

 function test(arr) { } 
+7
javascript arrays
source share
3 answers

If you have an array, for example, of five elements, the middle element is at index two:

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

Dividing the length into two and using Math.round will give you an index of three, not two, so you first need to subtract one from the length:

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

In your question, you say that you should use Math.round , but if this is not a requirement, you can get the same result using Math.floor :

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

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

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

Get the index in the middle of the array:

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

Single line:

 var value = arr[arr.length / 2 | 0]; 
+8
source share

You can also try this:

 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

+2
source share

All Articles