Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

sorting - JavaScript: Sort based on several methods simultaneously

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...