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


当前回答

价格降序:

homes.sort((x,y) => {return y.price - x.price})

价格升序:

homes.sort((x,y) => {return x.price - y.price})

其他回答

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

这是一个更灵活的版本,允许您创建可重用的排序函数,并按任何字段排序。

const sort_by=(字段,反转,引物)=>{常量键=引物?函数(x){返回底漆(x[字段])} :函数(x){返回x[字段]};反转=!颠倒1 : -1;返回函数(a,b){返回a=键(a),b=键(b),反转*((a>b)-(b>a));}}//现在您可以随意按任何字段排序。。。const homes=[{h_id:“3”,城市:“达拉斯”,州:“TX”,邮编:“75201”,价格:“162500”},{h_id:“4”,城市“贝弗利山”,州“CA”,邮编“90210”,价格“319250”},{h_id:”5“,城市:”纽约“,州:”NY“,邮编:”00010“,价格:”962500“}];//按价格从高到低排序console.log(homes.sort(sort_by('price',true,parseInt)));//按城市排序,不区分大小写,A-Zconsole.log(homes.sort(sort_by('city',false,(a)=>a.toUpperCase())));

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
    }
})

如果不想使用任何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(家);

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

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