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


当前回答

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

其他回答

您可以将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);
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
    }
})

按价格升序排序:

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});

或ES6版本之后:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

这里可以找到一些文档。

对于降序,可以使用

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

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

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();

        }));
    }


}

如果不想使用任何sort()方法,可以使用以下方法

函数sortObj(obj){设numArr=[]//仅包含价格作为Number的数组让sortedObj=[];对象映射((x)=>{numArr.push(数字(x[“价格”]));});而(numArr.length>0){让minIndex=numArr.indexOf(数学最小(…numArr))//obj最便宜的住宅指数numArr.拼接(最小索引,1);排序对象推送(对象拼接(minIndex,1));//将最便宜的家庭从Homes Array拼接到sortedObj Array。}console.log(sortedObj);}var家=[{h_id:“3”,城市:“达拉斯”,状态:“TX”,邮编:“75201”,价格:“162500”,},{h_id:“4”,城市:“贝弗利山”,状态:“CA”,邮编:“90210”,价格:“319250”,},{h_id:“5”,城市:“纽约”,州:“NY”,邮编:“00010”,价格:“962500”,},];sortObj(家);