2017-08-09 66 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)两个值进行比较