If I've an array of numbers and I want get the number near to average how can I get that number!
First, I've tried to sort the array in an asc order, Secondly get the middle element which is the average.
Note: I used Math.floor
in case if the length of the array is odd not even number
const arr = [1, 6, 10, 3, 15, 9, 4, 7];
const arrSorted = arr.sort((a,b)=>a-b);
const nearToAVG = arrSorted[Math.floor(arr.length/2)];
console.log(nearToAVG); // 7
Is there any better way of getting the number near to the average in array?
CodePudding user response:
Another approach to achieve that By using:
reduce
to accumulate the sum and divide it by its length to get the average.map
iterate over that array and return each number with its nearByAVG (distance between that number and average).sort
by that property in order ascending and get the first one that has the minimum distance to average.
const arr = [1, 6, 10, 3, 15, 9, 4, 7];
const sum = arr.reduce((acc, curr)=>acc curr);
const avg = sum/arr.length;
const arrMaped = arr.map(num=>({num,nearByAVG: Math.abs(num-avg)}));
const arrSorted = arrMaped.sort((a,b)=>a.nearByAVG-b.nearByAVG);
console.log(arrSorted[0].num)
CodePudding user response:
You should add all the numbers and divide by the length of the array. Apart from that, the number the sorted array's center, is not the average of the numbers, just the median.
let numArray=[12,32,134,23,54,345,32,1]; //all elements numbers
let num=0;
for(let number of numArray) {num =number};
num/=numArray.length
console.log(num)
CodePudding user response:
Let's dissect this problem. You want the index with the nearest value to the average of the the array indices. To get that you may first calculate the sum of the array. Knowing the sum, you can do a second sweep of the array arr
to take the difference of each element from the average and store it in a variable. Lastly, you would update that variable if the difference between the average and the current index is closer to zero than the stored value. By the end of the array, you will have the answer you are looking for.
Here is a simple example of the above:
let sum = 0;
let nearest = arr[0];
for(let i = 0; i < arr.length; i ) {
sum = arr[i];
}
ave = sum / arr.length;
for(let i = 0; i < arr.length; i ) {
if((arr[i] - ave) < nearest) {
nearest = arr[i];
}
}
console.log(`average: ${ave}\nnearest: ${nearest}`);
// average: 6.875
// nearest: 7