How can I sort an indirect array with javascript?

前端 未结 4 1706
借酒劲吻你
借酒劲吻你 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:15

    Much Code, but it works :)

    For sort ASC:

    var test = [1, 4, 3, 4, 5, 6, 7, 8, 9];
    console.log("Original Array: " + test);
    var len = test.length;
    var indices = new Array(len);
    for (var i = 0; i < len; ++i) indices[i] = i;
    indices.sort(function (a, b) { return test[a] < test[b] ? -1 : test[a] > test[b] ? 1 : 0; });
    test.sort();
    console.log("Sort-ASC " + test);
    console.log("Index from Array " + indices);

    For sort DESC:

    var test = [1, 4, 3, 4, 5, 6, 7, 8, 9];
    console.log("Originales Array: " + test)
    var len = test.length;
    var indices = new Array(len);
    for (var i = 0; i < len; ++i) indices[i] = i;
    indices.sort(function (a, b) { return test[a] < test[b] ? -1 : test[a] > test[b] ? 1 : 0; });
    indices.reverse();
    test.sort();
    test.reverse();
    console.log("Sort-DESC " + test);
    console.log("Index from Array " + indices);

提交回复
热议问题