[英]Sort Array after closest Solution
I have an unsorted array with results of an calculation:我有一个未排序的数组,其中包含计算结果:
const solution = 955
const unsortedArray =
[
[["solution result cab"],[955.709]],
[["solution result abc"],[951.11]],
[["solution result cba"],[954.709]],
[["solution result bac"],[957.709]]
]
I want to sort the array after +/- the closest deviation of the solution:我想在解决方案的 +/- 最接近偏差之后对数组进行排序:
[
[["solution result cab"],[955.709]],
[["solution result cba"],[954.709]],
[["solution result bac"],[957.709]],
[["solution result abc"],[951.11]]
]
Is there some way to apply a range comparison into sort()
or is there a better solution?有什么方法可以将范围比较应用于
sort()
还是有更好的解决方案?
You can make a compare function that will compare the two elements' absolute differences from the solution.您可以进行比较 function 将比较两个元素与解决方案的绝对差异。 A positive number means the first element is bigger.
正数表示第一个元素更大。 A negative one means the second is bigger.
一个负数意味着第二个更大。
function compare(a, b) {
const aAbs = Math.abs(a[1][0] - solution);
const bAbs = Math.abs(b[1][0] - solution);
return aAbs - bAbs;
}
Then you can run unsortedArray.sort(compare)
.然后你可以运行
unsortedArray.sort(compare)
。
Per the documentation of Array.prototype.sort , you can supply a sorting function:根据Array.prototype.sort 的文档,您可以提供排序 function:
const compareDeviationFrom = (solution) => {
(resA, resB) => Math.abs(resA[1][0] - solution) - Math.abs(resB[1][0] - solution)
}
unsortedArray.sort(compareDeviationFrom(solution))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.