gpt4 book ai didi

javascript - 索引数组的自然排序对象

转载 作者:行者123 更新时间:2023-11-30 08:26:12 25 4
gpt4 key购买 nike

我有这个结构,我无法控制它,需要由客户进行排序。各种数组的索引彼此相关,即 client[0] 与 suites[0] 相关。这个结构可以这样排序吗?

当前结构:

'client' : [ Bravo,Alpha, 1 Delta, 2 Charlie],
'locations' : [ 2,1,3,4 ],
'suites' : [ B,A,C,D ],
'ids' : [ 16,18,25,65 ]

预期输出:

'client' : [ 1 Delta, 2 Charlie, Alpha,Bravo ],
'locations' : [ 3,4,1,2 ],
'suites' : [ C,D,A,B ],
'ids' : [ 25,65,18,16 ]

最佳答案

你可以使用 sorting with mapString#localeCompare带有选项

sensitivity

Which differences in the strings should lead to non-zero result values. Possible values are:

  • "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
  • "accent": Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
  • "case": Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
  • "variant": Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.

The default is "variant" for usage "sort"; it's locale dependent for usage "search".

numeric

Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are true and false; the default is false. This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. Implementations are not required to support this property.

var object = { client: ['Bravo', 'Alpha', '1 Delta', '2 Charlie'], locations: [2, 1, 3, 4], suites: ['B', 'A', 'C', 'D'], ids: [16, 18, 25, 65] },
indices = object.client.map((_, i) => i);

indices.sort((a, b) => object.client[a].localeCompare(object.client[b], undefined, { numeric: true, sensitivity: 'base' }));

Object.keys(object).forEach(function (key) {
object[key] = indices.map(i => object[key][i]);
});

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 索引数组的自然排序对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311216/

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