我使用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属性按升序或降序对对象进行排序?


当前回答

使用lodash.sortBy(使用commonjs的说明,您也可以将cdn的脚本include标记放在html的顶部)

var sortBy = require('lodash.sortby');
// or
sortBy = require('lodash').sortBy;

降序

var descendingOrder = sortBy( homes, 'price' ).reverse();

升序

var ascendingOrder = sortBy( homes, 'price' );

其他回答

我参加聚会有点晚了,但下面是我整理的逻辑。

function getSortedData(data, prop, isAsc) {
    return data.sort((a, b) => {
        return (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1)
    });
}

这是《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“}// ]

使用以下代码创建函数并根据输入进行排序

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"

 }];

 function sortList(list,order){
     if(order=="ASC"){
        return list.sort((a,b)=>{
            return parseFloat(a.price) - parseFloat(b.price);
        })
     }
     else{
        return list.sort((a,b)=>{
            return parseFloat(b.price) - parseFloat(a.price);
        });
     }
 }

 sortList(homes,'DESC');
 console.log(homes);
function sortByProperty(home){
    return home.price
}

sortByProperty按价格获取属性。将来,您可能希望按“zip”或字符串值“city”对数据进行排序。您需要在上面的函数中更改home.price

// if you want descending order change this to false
// if you are on react.js you could set this with useState
const ascending=true
// Initially "b" is the index-1 item and "a" is the index-0 item
homes.sort((a,b)=>{
     //initially 0th index
     const first=sortByProperty(a)
     // initially 1st index 
     const second=sortByProperty(b)
     
     // if you multiply by -1 it will be descending 
     const sortOrder=ascending ? 1 : -1
     if (typeof first==="number"){
            return (first-second) * sortOrder
    } else {
           // this will compare the string values
           return (first.localeCompare(second)) * sortOrder
    }
})

这里是以上所有答案的顶点。

Fiddle验证:http://jsfiddle.net/bobberino/4qqk3/

var sortOn = function (arr, prop, reverse, numeric) {

    // Ensure there's a property
    if (!prop || !arr) {
        return arr
    }

    // Set up sort function
    var sort_by = function (field, rev, primer) {

        // Return the required a,b function
        return function (a, b) {

            // Reset a, b to the field
            a = primer(a[field]), b = primer(b[field]);

            // Do actual sorting, reverse as needed
            return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
        }

    }

    // Distinguish between numeric and string to prevent 100's from coming before smaller
    // e.g.
    // 1
    // 20
    // 3
    // 4000
    // 50

    if (numeric) {

        // Do sort "in place" with sort_by function
        arr.sort(sort_by(prop, reverse, function (a) {

            // - Force value to a string.
            // - Replace any non numeric characters.
            // - Parse as float to allow 0.02 values.
            return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));

        }));
    } else {

        // Do sort "in place" with sort_by function
        arr.sort(sort_by(prop, reverse, function (a) {

            // - Force value to string.
            return String(a).toUpperCase();

        }));
    }


}