[英]How to customize sort an array
I'm trying to sort an array of objects in JS, but it doesn't work for some reason.我正在尝试对 JS 中的对象数组进行排序,但由于某种原因它不起作用。 The array I requested from API may contain numbers, upper and lower case letters, and some Chinese characters.
我从 API 请求的数组可能包含数字、大小写字母和一些汉字。
eg:例如:
const arr = [
{ "title": "!Test Segment and CSV" },
{ "title": "&test (SC)" },
{ "title": "1234test (SC)" },
{ "title": "AAShop1 (SC)" },
{ "title": "AAShop2(SC)" },
{ "title": "ABCshop123 (SC)" },
{ "title": "adidas Outlet" },
{ "title": "AIGLE" },
{ "title": "American Eagle" },
{ "title": "Châteraisé" },
{ "title": "Tekcent" },
{ "title": "반찬 & COOK" },
{ "title": "始祖鸟" },
{ "title": "春水堂" },
{ "title": "稻成" }
];
I want it sorted according to the following rules.我希望它按照以下规则排序。
sort a after A在 A 之后排序
sort B after A在 A 之后排序 B
sort Ac after ABC在 ABC 之后排序 Ac
{ "title": "!Test Segment and CSV" }, { "title": "&test (SC)" }, { "title": "1234test (SC)" }, { "title": "AAShop1 (SC)" }, { "title": "AAShop2(SC)" }, { "title": "ABCshop123 (SC)" }, { "title": "AIGLE" }, { "title": "American Eagle" }, { "title": "adidas Outlet" }, { "title": "Châteraisé" }, { "title": "Tekcent" }, { "title": "始祖鸟" }, { "title": "春水堂" }, { "title": "稻成" }, { "title": "반찬 & COOK" }
Thanks in advance for any help!提前感谢您的帮助!
.sort()
and .localeCompare()
. .sort()
和.localeCompare()
。 Note, in the OP, the input array is already sorted correctly so in this answer I have jumbled the order of the input array to demonstrate that the code functions correctly.请注意,在 OP 中,输入数组已经正确排序,因此在这个答案中,我混淆了输入数组的顺序以证明代码正常运行。
const data = [{ "title": "BB" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "AA" }, { "title": "Ba" }, { "title": "ABC" }]; const output = data.sort((a, b) => a.title.localeCompare(b.title)); console.log(output);
You just need to sort it on lower case.您只需要按小写字母对其进行排序。
let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }] let sortList = myArr.sort(function (a, b) { return a.title.toLowerCase() > b.title.toLowerCase() }) console.log(sortList)
You can simply achieve that without manipulating a string into a lowerCase
with the only help of a simple Array.sort()
method.您只需借助简单的
lowerCase
Array.sort()
方法即可轻松实现此目的,而无需将字符串操作为小写。
Live Demo :现场演示:
let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }]; let sortedArr = myArr.sort((a, b) => { return a.title - b.title }); console.log(sortedArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.