我使用AJAX获取了以下对象,并将它们存储在数组中:

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": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

如何创建一个函数,仅使用JavaScript按price属性按升序或降序对对象进行排序?


当前回答

使用此函数

const r_sort = (a, b, field, asc) => {
    let reverse = asc ? 1 : -1;
    if (a[field] > b[field]) {
        return 1 * reverse;
    }
    else if (b[field] > a[field]) {
        return -1 * reverse;
    }
    else {
        return 0;
    } }

//用法:

homes = homes.sort((a,b) => r_sort(a,b,price,true)) // true for ascending and false for descending

其他回答

 function compareValues(key, order = 'asc') {
  return function innerSort(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
    );
  };
}

http://yazilimsozluk.com/sort-array-in-javascript-by-asc-or-desc

我还处理了一些评级和多个字段排序:

arr = [
    {type:'C', note:834},
    {type:'D', note:732},
    {type:'D', note:008},
    {type:'F', note:474},
    {type:'P', note:283},
    {type:'P', note:165},
    {type:'X', note:173},
    {type:'Z', note:239},
];

arr.sort(function(a,b){        
    var _a = ((a.type==='C')?'0':(a.type==='P')?'1':'2');
    _a += (a.type.localeCompare(b.type)===-1)?'0':'1';
    _a += (a.note>b.note)?'1':'0';
    var _b = ((b.type==='C')?'0':(b.type==='P')?'1':'2');
    _b += (b.type.localeCompare(a.type)===-1)?'0':'1';
    _b += (b.note>a.note)?'1':'0';
    return parseInt(_a) - parseInt(_b);
});

后果

[
    {"type":"C","note":834},
    {"type":"P","note":165},
    {"type":"P","note":283},
    {"type":"D","note":8},
    {"type":"D","note":732},
    {"type":"F","note":474},
    {"type":"X","note":173},
    {"type":"Z","note":239}
]

一个简单的代码:

var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];let sortByPrice=homes.sort(函数(a,b){return parseFloat(b.price)-parseFlat(a.price);});对于(var i=0;i<sortByPrice.length;i++){document.write(sortByPrice[i].h-id+“”+sortByPrice[i].city+“”+按价格排序[i].state+''+sortByPrice[i].zip+“”+sortByPrice[i].price);document.write(“<br>”);}

您可以将JavaScript排序方法与回调函数一起使用:

function compareASC(homeA, homeB)
{
    return parseFloat(homeA.price) - parseFloat(homeB.price);
}

function compareDESC(homeA, homeB)
{
    return parseFloat(homeB.price) - parseFloat(homeA.price);
}

// Sort ASC
homes.sort(compareASC);

// Sort DESC
homes.sort(compareDESC);

这是《JavaScript:TheGoodParts》一书中优雅实现的一个略微修改版本。

注意:此版本的by是稳定的。它在执行下一个链式排序时保留第一个排序的顺序。

我给它添加了isAscending参数。还将它转换为ES6标准和作者推荐的“更新”好部件。

您可以按多个财产进行升序排序、降序排序和链式排序。

const by=函数(name,minor,isAscending=true){constreverseMultliplier=isAscending?1 : -1;返回函数(o,p){设a,b;let结果;if(o&&p&&typeof o==“object”&&typeof p===“object”){a=o[名称];b=p[名称];如果(a===b){返回minor类型==“函数”?小调(o,p):0;}if(a的类型==b的类型){结果=a<b-1 : 1;}其他{结果=a的类型<b的类型-1 : 1;}返回结果*reverseMultilier;}其他{投掷,投掷{name:“错误”,消息:“按+name排序时需要一个对象”};}};};设s=[{first:“乔”,last:“贝瑟”},{first:“Moe”,last:“Howard”},{first:“Joe”,last:“DeRita”},{first:“Shemp”,last:“Howard”},{first:“Larry”,last:“Fine”},{第一个:“卷毛”,最后一个:“霍华德”}];//排序方式:第一个升序,最后一个升序s.sort(按(“first”,按(“last”)));console.log(“排序方式:第一个升序,最后一个升序:”,s);//"[//{“第一”:“卷毛”,“最后”:“霍华德”},//{“第一”:“乔”,“最后”:“贝瑟”}<======//{“第一”:“乔”,“最后”:“德丽塔”}<======//{“第一”:“拉里”,“最后”:“好”},//{“第一”:“莫”,“最后”:“霍华德”},//{“first”:“Shemp”,“last”:”Howard“}// ]//排序方式:第一个升序,最后一个降序s.sort(按(“first”,按(“last”,0,false)));console.log(“排序方式:第一个升序,最后一个降序:”,s);//"[//{“第一”:“卷毛”,“最后”:“霍华德”},//{“第一”:“乔”,“最后”:“德丽塔”}<========//{“第一”:“乔”,“最后”:“贝瑟”}<========//{“第一”:“拉里”,“最后”:“好”},//{“第一”:“莫”,“最后”:“霍华德”},//{“first”:“Shemp”,“last”:”Howard“}// ]