javascript - 如何使用键和排序顺序对嵌套数组进行排序

标签 javascript arrays sorting

我正在尝试根据键和排序顺序对嵌套数组实现多重排序。

我可以根据键和顺序对数组进行排序

我已经完成了以下用于对数组进行排序的代码,

return array.sort((a, b) => {
      let i = 0, result = 0;
      while (i < sortBy.length && result === 0) {
        if (typeof a[sortBy[i].prop] == "string") {
          result = sortBy[i].direction * (a[sortBy[i].prop].toString() < b[sortBy[i].prop].toString() ? -1 : (a[sortBy[i].prop].toString() > b[sortBy[i].prop].toString() ? 1 : 0));
        } else {
          result = sortBy[i].direction * (a[sortBy[i].prop] < b[sortBy[i].prop] ? -1 : (a[sortBy[i].prop] > b[sortBy[i].prop] ? 1 : 0));
        }
        i++;
      }
      return result;
    });

我的输入数据如下,

array = [{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }, { x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' }];
sortBy= [{ 'prop': 'b', 'direction': 1 }, { 'prop': 'd', 'direction': 1}];

我希望得到如下输出,

array = [{ x: [{ d: 5 }, { d: 6 }, { d: 7 }, { d: 8 }], b: 's' },{ x: [{ d: 1 }, { d: 2 }, { d: 3 }, { d: 4 }], b: 'v' }];

但我得到以下结果,

array = [{ x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' },{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }];

我一直在思考如何解决这个逻辑问题。谁能帮我解决这个问题。

最佳答案

你很接近,你要做的是在具有属性 x 的内部数组上调用你的排序方法。然后后记在原始数组上调用它。这将首先使用 d 属性对子数组进行排序,然后通过 b 对外部数组进行排序。

array = [{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }, { x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' }];
sortBy= [{ 'prop': 'b', 'direction': 1 }, { 'prop': 'd', 'direction': 1}];

function sortFunc(a, b) {
  let i = 0, result = 0;
  while (i < sortBy.length && result === 0) {
    if (typeof a[sortBy[i].prop] == "string") {
      result = sortBy[i].direction * (a[sortBy[i].prop].toString() < b[sortBy[i].prop].toString() ? -1 : (a[sortBy[i].prop].toString() > b[sortBy[i].prop].toString() ? 1 : 0));
    } else {
      result = sortBy[i].direction * (a[sortBy[i].prop] < b[sortBy[i].prop] ? -1 : (a[sortBy[i].prop] > b[sortBy[i].prop] ? 1 : 0));
    }
    i++;
  }
  return result;
}

array.forEach(arr => arr.x = arr.x.sort(sortFunc));
array = array.sort(sortFunc);
console.log(array);
    

关于javascript - 如何使用键和排序顺序对嵌套数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644947/

相关文章:

javascript - CSS/JS : fixed header with variable size - dynamic body top-margin

javascript - 页面在 iPhone 中存在虚拟键盘时向上滚动

javascript - GmailApp、getDate 和排序

java - 排序列表后,如何将列表中的对象取回它们原来的位置?

c - C中链表的合并排序代码仅对一半元素进行排序

javascript - JS Array.prototype.filter with Array 扩展类构造函数调用

javascript - 检查数组中是否有重复项

python - 如何在Python中获取数组中所有NaN元素的索引?

arrays - Perl-我在寻找什么功能?将多个规则分配给指定结果

javascript - HTML5 拖放,放下的 div 从放下的位置移动一点