gpt4 book ai didi

javascript - 对其中包含字符串的数组进行排序

转载 作者:搜寻专家 更新时间:2023-10-31 23:17:33 24 4
gpt4 key购买 nike

我正在尝试对其中包含字符串数组的数组进行排序。它类似于这个问题 ( Sort an array with arrays in it by string ) 但我不确定如何实现它。我的数组如下

var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];

我试图按名称或内部数组的第二个参数按字母顺序(不区分大小写)对其进行排序。之后,如果有两个元素具有相同的第二个参数,我想按第一个参数排序。我尝试使用以下但没有成功,也没有真正明白为什么。任何人都可以建议:

function Comparator(a,b){
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}

var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];

myArray = myArray.sort(Comparator);

要在第二个参数之后对第一个参数进行排序,我会这样做吗?

   function Comparator(a,b){
if (a[1] < b[1]){
if (a[2] < b[2]) return -1
if (a[2] > b[2]) return 1;
}
return -1;
}
if (a[1] > b[1]) return 1;{
if (a[2] < b[2]) return -1
if (a[2] > b[2]) return 1;
}
return 1;
}
return 0;
}

var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];

myArray = myArray.sort(Comparator);

最佳答案

你可以编码:

function Comparator(a, b) {
// you can use the `String.prototype.toLowerCase()` method
// if the comparison should be case insensitive
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
}

上述函数首先根据数组的第二个元素对元素进行排序。如果第二个元素相等,则根据第一个元素对它们进行排序,如果 a[1] === b[1]a[0] === b[0] 它返回 0,这使 ab 位置保持不变。

From MDN Array.prototype.sort documentation :

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.

关于javascript - 对其中包含字符串的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930010/

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