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

Categories

In my project, I need to sort an array that contain index of an other array (it's item). I've search for many hours, but I did not find anyone with my problem.

var arr = [1, 4, 3, 4, 5, 6, 7, 8, 9];
function sorting(){
    let arr2 = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    //sorting code
}

Now, I want to sort arr2, so when I loop through it with this kind of code (under this paragraph), I access arr with the index in the sorted array (arr2).

  arr[arr2[i]]

My first move was to use arr2.sort(function(a,b){arr[a] - arr[b]}, but each time the sort wasn't good. I attempt to make my own sorting function, but my problem stayed.

To summarize, I want to sort arr2 so when I loop through it, I get the value of arr in ascending (or descending) order.

EDIT I fixe this problem, but another appears, when I applied the arr2 on my html, the order mess up.

    var arr = [1, 4, 3, 4, 5, 6, 7, 8, 9];
    function sorting(){
        let arr2 = [0, 1, 2, 3, 4, 5, 6, 7, 8];
        //The sorting block code (done)
        z = document.getElementsByClassName("triable"); //this is on what I applied arr2
        for (let i = 0; i < z.length; i++){
            z[i].style.order = arr2[i]; //this line work, but doesn't correctly do what I what it to do
        }
    }

For html, I have some div with a class "triable" and the code above this need to applied a css style (order) so the div visually change of position

See Question&Answers more detail:os

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

1 Answer

You need to return the delta. Otherwise the callback returns undefined for each call.

arr2.sort(function(a, b) {
    return arr[b] - arr[a];
});

For adding the right order, you need ot take the index from indices to address the right element and assign i as style order value.

function sort() {
    var array = [1, 4, 3, 4, 5, 6, 7, 8, 9],
        z = document.getElementsByClassName("triable");

    [...array.keys()]
        .sort((a, b) => array[b] - array[a])
        .forEach((v, i) => z[v].style.order = i);
}
<button onclick="sort()">sort</button><br>
<div style="display: flex;">
<span class="triable">1</span>
<span class="triable">4</span>
<span class="triable">3</span>
<span class="triable">4</span>
<span class="triable">5</span>
<span class="triable">6</span>
<span class="triable">7</span>
<span class="triable">8</span>
<span class="triable">9</span> 
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...