js:对二维数组进行排序

时间:2021-04-20 17:00:38

标签: javascript arrays

还可以做些什么来对二进制数组的 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);

2 个答案:

答案 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);