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


当前回答

如果使用Undercore.js,请尝试sortBy:

// price is of an integer type
_.sortBy(homes, "price"); 

// price is of a string type
_.sortBy(homes, function(home) {return parseInt(home.price);}); 

其他回答

我最近编写了一个通用函数,如果您想使用它,可以为您管理它。

/**
 * Sorts an object into an order
 *
 * @require jQuery
 *
 * @param object Our JSON object to sort
 * @param type Only alphabetical at the moment
 * @param identifier The array or object key to sort by
 * @param order Ascending or Descending
 *
 * @returns Array
 */
function sortItems(object, type, identifier, order){

    var returnedArray = [];
    var emptiesArray = []; // An array for all of our empty cans

    // Convert the given object to an array
    $.each(object, function(key, object){

        // Store all of our empty cans in their own array
        // Store all other objects in our returned array
        object[identifier] == null ? emptiesArray.push(object) : returnedArray.push(object);

    });

    // Sort the array based on the type given
    switch(type){

        case 'alphabetical':

            returnedArray.sort(function(a, b){

                return(a[identifier] == b[identifier]) ? 0 : (

                    // Sort ascending or descending based on order given
                    order == 'asc' ? a[identifier] > b[identifier] : a[identifier] < b[identifier]

                ) ? 1 : -1;

            });

            break;

        default:

    }

    // Return our sorted array along with the empties at the bottom depending on sort order
    return order == 'asc' ? returnedArray.concat(emptiesArray) : emptiesArray.concat(returnedArray);

}

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

如果您有符合ES6标准的浏览器,您可以使用:

箭头功能Number()函数sort()函数

升序和降序之间的区别是比较函数返回的值的符号:

var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price));
var descending = homes.sort((a, b) => Number(b.price) - Number(a.price));

下面是一个工作代码片段:

var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];homes.sort((a,b)=>编号(a.price)-编号(b.price));console.log(“升序”,homes);homes.sort((a,b)=>编号(b.price)-编号(a.price));console.log(“下降”,homes);

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

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

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