如何在JavaScript中套用嵌套排序

前端之家收集整理的这篇文章主要介绍了如何在JavaScript中套用嵌套排序 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在javascript中有以下对象数组

[
{'name' : 'Ram','age': 10,'city' : 'a'},{'name' : 'Shyam','age': 5,{'name' : 'Aditya','city' : 'b'},'city' : 'a'}]

现在,我需要应用嵌套排序.

用户可以按名称,年龄,城市对上述集合进行排序.

假设用户要求按名称排序,则排序后的数组将看起来相似.

[
{'name' : 'Aditya','city' : 'b'}
{'name' : 'Mohan','age': 50,'city' : 'b'}
{'name' : 'Ram',用户单击以按年龄(asc)进行排序,但这不会打扰上面的数组.

它看起来应该像

[
{'name' : 'Aditya','city' : 'a'}]

但是如果假设用户要求按年龄对上述排序说明进行排序,那么它应该看起来像

 [
{'name' : 'Aditya','city' : 'a'}

这就是我当前要排序的函数的样子.

let compareObjects = (key,order = 'asc') => {
return function (a,b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
        // property doesn't exist on either object
        return 0;
    }

    const varA = (typeof a[key] === 'string') ?
        a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string') ?
        b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
        comparison = 1;
    } else if (varA < varB) {
        comparison = -1;
    }
    return (
        (order == 'desc') ? (comparison * -1) : comparison
    );
}}


 arrOfObjects.sort(compareObjects('age'));

但是我不知道如何应用嵌套排序?

谢谢!

最佳答案
compareObjects方法可以接受{key:order}对象数组(sortBy).然后用for … of循环sortBy数组,提取键和顺序,并比较直到结果不为0,或者如果它们都相等则返回0.

const compareStr = (a,b) => a.toLowerCase().localeCompare(b.toLowerCase())
const compareNumber = (a,b) => a - b

const compareBy = new Map([
  ['name',compareStr],['age',compareNumber],['city',])

const compareObjects = sortBy => (a,b) => {
  for (const srt of sortBy) { // iterate sortBy
    const [key,order] = Object.entries(srt)[0]; // extract key|order pairs
    const sorter = compareBy.get(key) // get the sorter from the Map

    if (!sorter || !(key in a) || !(key in b)) continue // if no sorter or if key doesn't exist in either object continue to the next sorter

    const score = sorter(a[key],b[key]) // sort the current values

    if (score === 0) continue; // if score is 0 continue to next sorter

    return score * (order === 'asc' ? 1 : -1) // return the score multiplied by -1 for non asc values
  }

  return 0;
}

const data = [{"name":"Ram","age":10,"city":"a"},{"name":"Shyam","age":5,{"name":"Aditya","city":"b"},"city":"a"}]

const result = data.sort(compareObjects([
  { age: 'desc' },{ name: 'asc' }
]))

console.log(result)
原文链接:https://www.f2er.com/js/531294.html

猜你在找的JavaScript相关文章