How can I sort an indirect array with javascript?

前端 未结 4 1708
借酒劲吻你
借酒劲吻你 2020-12-10 22:42

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.

<         


        
4条回答
  •  长情又很酷
    2020-12-10 23:27

    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);
    }

    1 4 3 4 5 6 7 8 9

提交回复
热议问题