I'm trying to work out how to use multiple methods of sorting at once.
For example, say I have 3 ways of sorting numbers:
function weightedSort() {
var outputArea = document.getElementById("outputArea");
var distanceWeight = document.getElementById("distanceSlider").value;
var largestWeight = document.getElementById("largestSlider").value;
var smallestWeight = document.getElementById("smallestSlider").value;
var numbers = [1, 3, 4, 5, 7, 9, 13, 40, 500];
outputArea.value = numbers.sort(function(a, b) {
var distanceResult = Math.abs(4 - a) - Math.abs(4 - b);
var largestResult = b - a;
var smallestResult = a - b;
var distanceWeighted = distanceResult * distanceWeight;
var largestWeighted = largestResult * largestWeight;
var smallestWeighted = smallestResult * smallestWeight;
return distanceWeighted + largestWeighted + smallestWeighted;
}).join("
");
}
<div>
<label for="distanceSlider">Closest to 4</label>
<input id="distanceSlider" type="range" min="0" max="1"value="0" step="0.01" oninput="weightedSort();">
<label for="largestSlider">Largest</label>
<input id="largestSlider" type="range" min="0" max="1" value="0" step="0.01" oninput="weightedSort();">
<label for="smallestSlider">Smallest</label>
<input id="smallestSlider" type="range" min="0" max="1" value="0" step="0.01" oninput="weightedSort();">
</div>
<textarea id="outputArea" rows="9" cols="20">
1
3
4
5
7
9
13
40
500
</textarea>
question from:
https://stackoverflow.com/questions/65895915/javascript-sort-based-on-several-methods-simultaneously 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…