簡體   English   中英

Javascript-根據對象值對帶有對象的數組進行排序

[英]Javascript - Sorting array with objects based on objects value

所以我試圖根據對象值對帶有對象的數組進行排序。

var mostCheapHistory [ { lowestTitle: title goes here, lowestPrice: 100 }, another obj, another, another } ]

我想根據價格對它們進行排序,因此我想到了:

var historyObj = mostCheapHistory[0];

for(var y in mostCheapHistory){
    nextObj = mostCheapHistory[y];

    console.log('Is '+ historyObj.lowestPrice + ' more as ' + nextObj.lowestPrice + ' ?');
    console.log(historyObj.lowestPrice > nextObj.lowestPrice);
    console.log('-----')
}

這是輸出...

Is 124.98 more as 124.98 ?
false
-----
Is 124.98 more as 18.59 ?
false
-----
Is 124.98 more as 25.9 ?
false
-----
Is 124.98 more as 26.99 ?
false
-----
Is 124.98 more as 34.76 ?
false
-----

這到底是怎么回事? 顯然,124.98大於34.76,但它給出的是假的?

使用以下代碼制作數組:

for(var x=0; x < items.length; x++){
            var title = items[x].title[0];
            var price = items[x].sellingStatus[0].currentPrice[0].__value__;

            var item = 
                { 
                    lowestPrice : price,
                    lowestTitle : title
                }

            if(x === 0){
                mostCheapHistory.push(item);                
            }
            else{
                for(var y=0; y < mostCheapHistory.length; y++){
                    if(mostCheapHistory[y].lowestPrice > price ){
                        if(mostCheapHistory.length < 5){
                            mostCheapHistory.push(item);
                            break;
                        }
                        else{
                            mostCheapHistory[y] = item;
                            break;
                        }
                    }
                }
            }
        }

使用預定義的排序功能:

mostCheapHistory.sort(function(a,b){
    return a.lowestPrice - b.lowestPrice;
}

+您的代碼可能會推送字符串而不是數字,這解釋了為什么124.98 > 34.76 => true但是'124.98' > '34.76' => false ,因為字符串比較中字符串'34 .76'大於'124.98'。
使用parseFloat()作為價格,然后再次檢查。

看起來,您正在比較字符串而不是數字值。 如果您說(在注釋中),則表示排序功能

array.sort((a, b) =>  a.lowestPrice - b.lowestPrice);

解決了您的問題,然后在此排序回調中使用隱式強制轉換以減號-運算符編號。

結果是一個排序數組,其值作為字符串。

您可以使用Array.prototype.sort()根據價格對它們進行排序( 請參閱MDN文檔

例如

var data = [
{
  title: "title1",
  value: 123
},
{
  title: "title2",
  value: 324
},
{
  title: "title3",
  value: 142
}];

var sorted = data.sort(function(a, b) {
  return a.value > b.value;
});

我認為lowestPrice的類型是字符串而不是浮點型,請使用parseFloat(historyObj.lowestPrice)來比較兩個值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM