如何使用 JavaScript 排序对多列进行排序?

How to sort on multiple columns using JavaScript sort?

我有以下数组需要根据搜索文本进行排序 'John'。

  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 5, firstName: 'John', lastName: 'Doe'},


];

预期输出:

数组应首先按昵称(带搜索文本)排序,然后按姓氏(带搜索文本)排序。如果 nickName 不存在,那么它应该按照 ASC 排序顺序相对于 firstName(带有搜索文本)进行排序。 注意:它应该将搜索文本词视为'John'

这种排序类似于手机联系人应用中的“使用排序搜索”

[
  // sort with nickName as higher relevance considering search text as John
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  // sort with lastName considering search text
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  // sort  with firstName as nickName is null
  {id: 5, firstName: 'John', lastName: 'Doe'},



];

我尝试了 localeMethod

function sortByLocale(user1, user2) {
   var sortByNickName = user1.nickName.toLowerCase().localeCompare(user2.nickName.toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortByNickName || sortByLastName;
}

但结果排序时没有考虑搜索文本。 我可以看到一种方法是创建三个不同的数组并对它们进行排序并将这些排序的数组组合起来 任何帮助将不胜感激。

编辑:不考虑具有搜索文本值的不匹配对象

您可以对想要的订单进行两次迭代

  1. 一个用于想要的字符串
  2. 其余顺序

var data = [{ id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith' },
  { id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew' },
  { id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John' },
  { id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John' },
  { id: 5, firstName: 'John', lastName: 'Doe' }
],
    search = 'john',
    check = (s => (o, k) => (o[k] || '').toLowerCase() === search)(search),
    keys = ['nickName', 'lastName', 'firstName'];

data.sort((a, b) => {
    const
        fns = [
            k => d = check(b, k) - check(a, k),
            k => d = (a[k] || '').localeCompare(b[k] || '')
        ];
    let d = 0;
    fns.some(fn => keys.some(fn));
    return d;
});

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

只需添加第一个按名称搜索

function checkSearch (value)  {
   return (value.nickName === 'John') * -3 ||
      (value.lastName === 'John') * -2 ||
      (value.firstName === 'John') * -1 ||
      0
}

function sortByLocale(user1, user2) {
   var sortBySearch = checkSearch(user1) - checkSearch(user2)

   var sortByNickName = (user1.nickName || '').toLowerCase().localeCompare((user2.nickName || '').toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortBySearch || sortByNickName || sortByLastName;
}