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

时间:2020-06-02 16:54:38

标签: javascript arrays sorting custom-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'},


];

预期输出:

首先应使用昵称(带有搜索文本)对数组进行排序,然后使用姓氏(带有搜索文本)对数组进行排序。如果不存在昵称,则应使用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;
}

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

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

2 个答案:

答案 0 :(得分:1)

您可以为所需订单进行两次迭代

  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; }

答案 1 :(得分:1)

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

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;
}
相关问题