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


当前回答

一个简单的代码:

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

其他回答

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

嗨,看完这篇文章后,我根据自己的需要制作了一个sortComprator,它具有比较多个json属性的功能,我想和大家分享一下。

此解决方案仅按升序比较字符串,但该解决方案可以方便地扩展到每个属性以支持:反向排序、其他数据类型、使用区域设置、强制转换等

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"

}];

// comp = array of attributes to sort
// comp = ['attr1', 'attr2', 'attr3', ...]
function sortComparator(a, b, comp) {
    // Compare the values of the first attribute
    if (a[comp[0]] === b[comp[0]]) {
        // if EQ proceed with the next attributes
        if (comp.length > 1) {
            return sortComparator(a, b, comp.slice(1));
        } else {
            // if no more attributes then return EQ
            return 0;
        }
    } else {
        // return less or great
        return (a[comp[0]] < b[comp[0]] ? -1 : 1)
    }
}

// Sort array homes
homes.sort(function(a, b) {
    return sortComparator(a, b, ['state', 'city', 'zip']);
});

// display the array
homes.forEach(function(home) {
    console.log(home.h_id, home.city, home.state, home.zip, home.price);
});

结果是

$ node sort
4 Bevery Hills CA 90210 319250
5 New York NY 00010 962500
3 Dallas TX 75201 162500

还有另一种

homes.sort(function(a, b) {
    return sortComparator(a, b, ['city', 'zip']);
});

带有结果

$ node sort
4 Bevery Hills CA 90210 319250
3 Dallas TX 75201 162500
5 New York NY 00010 962500

虽然我知道OP想要对一组数字进行排序,但这个问题已经被标记为字符串相关类似问题的答案。事实上,上面的答案没有考虑对大小写很重要的文本数组进行排序。大多数答案采用字符串值并将其转换为大写/小写,然后以某种方式进行排序。我遵守的要求很简单:

按字母顺序A-Z排序同一单词的大写值应在小写值之前应将相同字母(A/A、B/B)的值分组在一起

我期望的是[A,A,B,B,C,C],但上面的答案返回A,B,C,A,B,C。实际上,我在这个问题上花了比我想要的时间更长的时间(这就是为什么我发布这个消息,希望它能帮助至少一个人)。虽然两个用户在注释中提到了localeCompare函数,但直到我在四处搜索时偶然发现了该函数之后,我才发现这一点。在阅读了String.product.localeCompare()文档后,我想到了这个:

var values = [ "Delta", "charlie", "delta", "Charlie", "Bravo", "alpha", "Alpha", "bravo" ];
var sorted = values.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: "upper" }));
// Result: [ "Alpha", "alpha", "Bravo", "bravo", "Charlie", "charlie", "Delta", "delta" ]

这告诉函数在小写值之前对大写值进行排序。localeCompare函数中的第二个参数是定义语言环境,但如果您将其保留为未定义,它会自动为您计算语言环境。

这同样适用于对对象数组进行排序:

var values = [
    { id: 6, title: "Delta" },
    { id: 2, title: "charlie" },
    { id: 3, title: "delta" },
    { id: 1, title: "Charlie" },
    { id: 8, title: "Bravo" },
    { id: 5, title: "alpha" },
    { id: 4, title: "Alpha" },
    { id: 7, title: "bravo" }
];
var sorted = values
    .sort((a, b) => a.title.localeCompare(b.title, undefined, { caseFirst: "upper" }));
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
    }
})

如果您有符合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);