0:"62", 1:8, 2:0, 3:"1-6ren">
gpt4 book ai didi

javascript - 按两个不同的值对 JavaScript 对象数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:22:10 25 4
gpt4 key购买 nike

我在 JavaScript 中有一个这样的对象:

myArray[0] -> 0:"62", 1:8, 2:0, 3:"11"
myArray[1] -> 0:"62", 1:8, 2:0, 3:"15"
myArray[2] -> 0:"48", 1:8, 2:0, 3:"04"
myArray[3] -> 0:"48", 1:8, 2:0, 3:"01"
myArray[4] -> 0:"62", 1:8, 2:0, 3:"12"
myArray[5] -> 0:"48", 1:8, 2:0, 3:"02"
myArray[6] -> 0:"62", 1:8, 2:0, 3:"14"
myArray[7] -> 0:"48", 1:8, 2:0, 3:"03"

我正在努力让它变成这样:

myArray[0] -> 0:"48", 1:8, 2:0, 3:"01"
myArray[1] -> 0:"48", 1:8, 2:0, 3:"02"
myArray[2] -> 0:"48", 1:8, 2:0, 3:"03"
myArray[3] -> 0:"48", 1:8, 2:0, 3:"04"
myArray[4] -> 0:"62", 1:8, 2:0, 3:"11"
myArray[5] -> 0:"62", 1:8, 2:0, 3:"12"
myArray[6] -> 0:"62", 1:8, 2:0, 3:"14"
myArray[7] -> 0:"62", 1:8, 2:0, 3:"15"

如您所见,我尝试先按 myArray[i][0] 排序,然后按 myArray[i][3] 排序基于 myArray[i][0] 作为索引。我设法使用

myArray[i][0] 排序
myObject.sort(function(a, b){ 
return parseInt(a) - parseInt(b);
});

如何在没有库的情况下完成此操作?

最佳答案

我建议使用链式比较函数在一次运行中进行排序。

How Array#sort() works:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

在这种情况下,比较函数有两组,一组用于排序索引 [0],一组用于排序索引 [3]。如果索引 [0] 处的值相等,则采用索引 [3] 的排序。这两个组都用逻辑或 || 链接起来。

var array = [["62", 8, 0, "11"], ["62", 8, 0, "15"], ["48", 8, 0, "04"], ["48", 8, 0, "01"], ["62", 8, 0, "12"], ["48", 8, 0, "02"], ["62", 8, 0, "14"], ["48", 8, 0, "03"]];

array.sort(function (a, b) {
return a[0].localeCompare(b[0]) || a[3].localeCompare(b[3]);
});

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

关于javascript - 按两个不同的值对 JavaScript 对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36067321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com