Javascript - sort by with arrays of variable length

Cyr*_*ris 2 javascript arrays sorting

Assume I have an array of options to sort by multiple scores, and those scores are an array of variable length

[
  #[Label, scores]
  ["Label6", [1]
  ["Label5", [1,5]
  ["Label2", [0,1,3,5],
  ["Label1", [0,1,2]
  ["Label3", [0,1,4],
  ["Label4", [1,4]
]
Run Code Online (Sandbox Code Playgroud)

I want to sort this list by evaluating array elements one by one. IE. I will first sort (ascending) by the score[0], then score[i+1] if it exists, etc. When score[i] does not exist, it should be considered as an infinite value (appear at the bottom)

This could gives the following output on the previous data :

list = [
  #[Label, scores]
  ["Label1", [0,1,2]  
  ["Label2", [0,1,3,5],
  ["Label3", [0,1,4],
  ["Label4", [1,4]
  ["Label5", [1,5]
  ["Label6", [1]
]
Run Code Online (Sandbox Code Playgroud)

如何编写此函数?是否有sortBy()像我们在其他语言中一样的native / ES6(或lodash / underscore)功能?(例如,在Ruby中,您只会list.sort_by(&:last)得到这种效果)。还是需要手动实施?

Nin*_*olz 5

您可以采用数组,并按相同的索引值排序。

开始时,将两个数组的最小长度作为迭代值的长度,并避免采用undefined

如果相同索引的两个值的增量不为零,则返回增量,否则继续下一个索引。

如果访问了所有索引而没有先前的返回值,则相同索引处的所有值都相等,直到两个数组的最小长度为止。在这种情况下,应按切换顺序返回两者长度的差值,因为较长的数组应排在首位。

var array = [["Label6", [1, 5]], ["Label2", [0, 1, 3, 5]], ["Label1", [0, 1, 2]], ["Label3", [0, 1, 4]], ["Label5", [1, 5, 2]], ["Label4", [1, 4]]];

array.sort(([, a], [, b]) => {
    var delta,
        index = 0,
        length = Math.min(a.length, b.length);

    while (index < length) {
        delta = a[index] - b[index];
        if (delta) return delta;
        index++;
    }

    return b.length - a.length;
});

console.log(array);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)