gpt4 book ai didi

javascript - 在 Javascript 中自然搜索带有数字和文本的对象数组

转载 作者:行者123 更新时间:2023-12-01 03:11:00 25 4
gpt4 key购买 nike

我有如下数组,我需要它仅在文本字段上应用自然排序。

    var data = [{
"text": "1001",
"value": "212121"
}, {
"text": "1002",
"value": "32435"
}, {
"text": "A101",
"value": "324124324"
}, {
"text": "A12",
"value": "567y54645"
}, {
"text": "A123",
"value": "534534"
}, {
"text": "A21",
"value": "34534534"
}, {
"text": "A210",
"value": "5345345"
}, {
"text": "A33",
"value": "234234234"
},
"text": "B2",
"value": "4234234"
}, {
"text": "D10000",
"value": "34234234"
}, {
"text": "EZH43NUT8SD",
"value": "534534534"
}, {
"text": "H287",
"value": "43435345"
}, {
"text": "Pkg test",
"value": "5345345"
}]

到目前为止我已经尝试过以下操作:

http://jsfiddle.net/wE7H2/3/

AngularJS - Sorting ng-repeat on string with numbers in them

最佳答案

您可以使用String#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 data = [{ text: "1001", value: "212121" }, { text: "1002", value: "32435" }, { text: "A101", value: "324124324" }, { text: "A12", value: "567y54645" }, { text: "A123", value: "534534" }, { text: "A21", value: "34534534" }, { text: "A210", value: "5345345" }, { text: "A33", value: "234234234" }, { text: "B2", value: "4234234" }, { text: "D10000", value: "34234234" }, { text: "EZH43NUT8SD", value: "534534534" }, { text: "H287", value: "43435345" }, { text: "Pkg test", value: "5345345" }, { text: "RRG46AXC3PO", value: "3434354" }, { text: "yoyo", value: "534534534" }];

data.sort(function (a,b) {
return a.text.localeCompare(b.text, undefined, { numeric: true, sensitivity: 'base' });
});

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

关于javascript - 在 Javascript 中自然搜索带有数字和文本的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45854631/

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