.sort optionally takes a function. The function takes 2 values at a time, and compares them:
- If the first value should sort higher than the second, the function should return a positive number.
- If the first value should sort lower than the second, the function should return a negative number.
- If the values are equal, the function should returns
0.
So, if you wanted to sort by dezibel in ascending order, you could do
arr.sort(function(a,b){
return a.dezibel- b.dezibel;
});
However, you want to sort by dezibel's distance from some number. To find the magnitude of the difference from 78 and the dezibel value, take the absolute value of the difference:
Math.abs(78 - a.dezibel)
Now, if we want to sort based on that value for each object, we can take the difference of that Math.abs call for both a and b:
arr.sort(function(a,b){
return Math.abs(78 - a.dezibel) - Math.abs(78 - b.dezibel);
});