gpt4 book ai didi

Javascript根据特定字符串对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 07:49:53 25 4
gpt4 key购买 nike

基本上,我正在尝试根据特定的字符串匹配对数组进行排序。我希望限定符 === 'oip' 排序到顶部

[
{
qualifier: 'abc',
},
{
qualifier: 'oip'
}
]

我将如何使用 x.sort((a,b) =>

最佳答案

应该这样做:

x.sort((a,b) => a === 'oip'? 1 : -1)

您可以阅读更多关于 sort here 的信息.

If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to an index lower 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 an index lower than a (i.e. b comes first).
  • 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.

此答案适用于 OP 所述的示例。然而,为了更完整(感谢指出 @Pointy ),这里是一个完整的版本:

x = [
{qualifier: 'abc'},
{qualifier: 'oip'},
{qualifier: 'def'},
{qualifier: 'gij'},
{qualifier: 'oip'},
];

y = x.sort((a, b) => {
if (a.qualifier === b.qualifier && a.qualifier === 'oip') {
return 0;
} else if (a.qualifier === 'oip') {
return -1;
} else if (b.qualifier === 'oip') {
return 1;
}else {
return a.qualifier > b.qualifier? 1 : -1;
}
});

关于Javascript根据特定字符串对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993007/

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