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


当前回答

更像LINQ的解决方案:

Array.prototype.orderBy = function (selector, desc = false) {
    return [...this].sort((a, b) => {
        a = selector(a);
        b = selector(b);

        if (a == b) return 0;
        return (desc ? a > b : a < b) ? -1 : 1;
    });
}

优势:

财产的自动补全扩展阵列原型不更改数组易于在方法链中使用

用法:

Array.prototype.orderBy=函数(选择器,desc=false){return[…this].sort((a,b)=>{a=选择器(a);b=选择器(b);如果(a==b)返回0;返回(desc?a>b:a<b)-1 : 1;});};var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];let sorted_homes=homes.orderBy(h=>parseFloat(h.price));console.log(“按价格排序”,sorted_homes);let sorted_homes_desc=homes.orderBy(h=>h.city,true);console.log(“按城市降序排序”,sorted_home_desc);

其他回答

有了ECMAScript 6,StoBor的答案可以更加简洁:

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

一个简单的代码:

var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];let sortByPrice=homes.sort(函数(a,b){return parseFloat(b.price)-parseFlat(a.price);});对于(var i=0;i<sortByPrice.length;i++){document.write(sortByPrice[i].h-id+“”+sortByPrice[i].city+“”+按价格排序[i].state+''+sortByPrice[i].zip+“”+sortByPrice[i].price);document.write(“<br>”);}

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

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

这可以通过一个简单的单行值of()排序函数实现。运行下面的代码片段以查看演示。

var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];console.log(“要首先对降序/最高排序,请使用运算符'<'”);homes.sort(函数(a,b){return a.price.valueOf()<b.price.vvalueOf(;});console.log(homes);console.log(“要首先对升序/最低排序,请使用运算符'>'”);homes.sort(函数(a,b){return a.price.valueOf()>b.price.vvalueOf(;});console.log(homes);