2017-08-09 69 views
1

所以我想我的排序陣列,基於對象的值對象..使用Javascript - 排序與對象數組基於對象的價值

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; 
         } 
        } 
       } 
      } 
     } 
+0

請加分類部分。 –

+0

它不排序任何東西,因爲我真的不能測試,如果一個值越大,作爲另一個你可以看到 –

+0

請加陣列的真實數據。 –

回答

1

使用預定義的排序功能:

的陣列使用此代碼所做

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()作爲價格,然後再次檢查。

+0

這也不說爲什麼在問題的代碼產生它是什麼居然問輸出。 – csmckelvey

+0

事實上,這個固定的問題,謝謝:)但仍然想知道爲什麼我得到了輸出 –

+0

個也許要附加字符串而不是數字,因此'124.98> 34.76 => TRUE'但是' '124.98'> '34 0.76' => FALSE' –

0

您可以將這些基於價格使用Array.prototype.sort(排序)(See MDN documentation

例如

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

看起來,你是比較字符串而非數值。如果你說(在評論),該排序功能

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

解決您的問題,然後在這種回調採用了隱式轉換與負-運營商數量。

結果是一個排序後的數組與值作爲字符串。

0

我覺得lowestPrice類型爲字符串不浮動,使用parseFloat(historyObj.lowestPrice)兩個值進行比較