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


当前回答

你需要两个功能

function desc(a, b) {
 return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function asc(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

然后可以将其应用于任何对象属性:

 data.sort((a, b) => desc(parseFloat(a.price), parseFloat(b.price)));

让数据=[{label:“一”,值:10},{label:“two”,值:5},{label:“three”,值:1},];//排序函数函数desc(a,b){返回b<a-1:b>a?1:b>=a?0:NaN;}函数asc(a,b){返回a<b-1:a>b?1:a>=b?0:NaN;}//描述(DESC)data.sort((a,b)=>desc(a.value,b.value));document.body.insert相邻HTML('之前','<strong>DESC排序</strong><pre>'+JSON.stringify(数据)+'</pre>');//美国科学院data.sort((a,b)=>asc(a.value,b.value));document.body.insert相邻HTML('之前','<strong>ASCending sorted</strong><pre>'+JSON.stringify(数据)+'</pre>');

其他回答

如果使用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);}); 

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

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

        }));
    }


}

仅对于元素值的普通数组:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]

var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]

对于对象数组:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]
homes.sort(function(a, b){
  var nameA=a.prices.toLowerCase(), nameB=b.prices.toLowerCase()
  if (nameA < nameB) //sort string ascending
    return -1 
  if (nameA > nameB)
    return 1
  return 0 //default return value (no sorting)
})

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

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