还可以做些什么来对二进制数组的 title
进行排序?
let ary = [
["search-type", [{
"title": "google",
"link": "https://"
},
{
"title": "wikipedia",
"link": "https://"
},
{
"title": "a-search",
"link": "https://"
},
{
"title": "c-search",
"link": "https://"
},
{
"title": "q-search",
"link": "https://"
}
]],
["tool-type", [{
"title": "remove bg",
"link": "https://"
},
{
"title": "q",
"link": "https://"
},
{
"title": "c",
"link": "https://"
},
{
"title": "3q",
"link": "https://"
}
]]
];
ary.forEach(array => {
array[1].sort(function(s, t) {
let a = s.title.toLowerCase();
let b = t.title.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
})
})
console.log(ary);
答案 0 :(得分:1)
localeCompare
。let ary = [["search-type", [{ title: "google", link: "https://" }, { title: "wikipedia", link: "https://" }, { title: "a-search", link: "https://" }, { title: "c-search", link: "https://" }, { title: "q-search", link: "https://" }]], ["tool-type", [{ title: "remove bg", link: "https://" }, { title: "q", link: "https://" }, { title: "c", link: "https://" }, { title: "3q", link: "https://" }]]];
ary.forEach((arr) =>
arr.forEach((v) =>
v instanceof Array &&
v.sort((a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: "base" }))
)
);
console.log(ary);
答案 1 :(得分:0)
是的,这可以简化。它本质上与您编写的函数相同,只是精简了。您也可以省略 0
return 语句。
let ary = [
['search-type', [
{ title: 'google', link: 'https://' },
{ title: 'wikipedia', link: 'https://' },
{ title: 'a-search', link: 'https://' },
{ title: 'c-search', link: 'https://' },
{ title: 'q-search', link: 'https://' }
]],
['tool-type', [
{ title: 'remove bg', link: 'https://' },
{ title: 'q', link: 'https://' },
{ title: 'c', link: 'https://' },
{ title: '3q', link: 'https://' }
]]
];
ary.forEach(e => e[1].sort((a,b) => a.title > b.title ? 1 : -1));
console.log(ary);
如果你想为相等的字符串保留 0 默认值,你可以使用这个:
let ary = [
['search-type', [
{ title: 'google', link: 'https://' },
{ title: 'wikipedia', link: 'https://' },
{ title: 'a-search', link: 'https://' },
{ title: 'c-search', link: 'https://' },
{ title: 'q-search', link: 'https://' }
]],
['tool-type', [
{ title: 'remove bg', link: 'https://' },
{ title: 'q', link: 'https://' },
{ title: 'c', link: 'https://' },
{ title: '3q', link: 'https://' }
]]
];
ary.forEach(e => e[1].sort((a,b) => a.title > b.title ? 1 : (a.title < b.title ? -1 : 0)));
console.log(ary);