为了账号安全,请及时绑定邮箱和手机立即绑定

如何按多个字段对象数组进行排序?

如何按多个字段对象数组进行排序?

扬帆大鱼 2019-06-17 17:17:34
如何按多个字段对象数组进行排序?从这里原始问题,如何在多个字段上应用排序?使用这种稍微调整的结构,我将如何排序城市(上升)&然后价格(下降)?var homes = [     {"h_id":"3",      "city":"Dallas",      "state":"TX",      "zip":"75201",      "price":"162500"},     {"h_id":"4",      "city":"Bevery Hills",      "state":"CA",      "zip":"90210",      "price":"319250"},     {"h_id":"6",      "city":"Dallas",      "state":"TX",      "zip":"75000",      "price":"556699"},     {"h_id":"5",      "city":"New York",      "state":"NY",      "zip":"00010",      "price":"962500"}     ];我喜欢事实甚于回答提供了一种通用的方法。在我计划使用这段代码的地方,我必须对日期和其他事情进行排序。“优化”对象的能力似乎很方便,如果不是有点麻烦的话。我试过建造这个回答一个很好的通用例子,但我运气不太好。
查看完整描述

4 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

对于非一般的、简单的解决您的确切问题的解决方案:

homes.sort(
   function(a, b) {          
      if (a.city === b.city) {
         // Price is only important when cities are the same
         return b.price - a.price;
      }
      return a.city > b.city ? 1 : -1;
   });


查看完整回答
反对 回复 2019-06-17
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

这里有一个简单的函数方法。使用数组指定排序顺序。预备若要指定降序,请执行以下操作。

var homes = [
    {"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":"162500"},
    {"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":"319250"},
    {"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"},
    {"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"}
    ];homes.sort(fieldSorter(['city', '-price']));// homes.sort(fieldSorter(['zip', '-state', 'price']));
     // alternativefunction fieldSorter(fields) {
    return function (a, b) {
        return fields            .map(function (o) {
                var dir = 1;
                if (o[0] === '-') {
                   dir = -1;
                   o=o.substring(1);
                }
                if (a[o] > b[o]) return dir;
                if (a[o] < b[o]) return -(dir);
                return 0;
            })
            .reduce(function firstNonZeroValue (p,n) {
                return p ? p : n;
            }, 0);
    };}

编辑:在ES6中,它甚至更短!

"use strict";

const fieldSorter = (fields) => (a, b) => fields.map(o => {

    let dir = 1;

    if (o[0] === '-') { dir = -1; o=o.substring(1); }

    return a[o] > b[o] ? dir : a[o] < b[o] ? -(dir) : 0;

}).reduce((p, n) => p ? p : n, 0);


const homes = [{"h_id":"3", "city":"Dallas", "state":"TX","zip":"75201","price":162500},     {"h_id":"4","city":"Bevery Hills", "state":"CA", "zip":"90210", "price":319250},{"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":556699},{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":962500}];

const sortedHomes = homes.sort(fieldSorter(['state', '-price']));


document.write('<pre>' + JSON.stringify(sortedHomes, null, '\t') + '</pre>')


查看完整回答
反对 回复 2019-06-17
  • 4 回答
  • 0 关注
  • 1518 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号