我有一份我想要排序的产品清单。 按价格和持续时间排序很容易。但我想找到最好的整体产品。
这是我到目前为止所做的:
var divList = $(".listing-item");
/* -------------------------------------- */
$("#btnPrice").click(function () {
divList.sort(function(a, b) {
return $(a).data("price")-$(b).data("price")
});
$("#list").append(divList);
});
/* -------------------------------------- */
$("#btnDuration").click(function () {
divList.sort(function(a, b) {
return $(a).data("duration")-$(b).data("duration")
});
$("#list").append(divList);
});
/* -------------------------------------- */
$("#btnBest").click(function () {
/* TBD */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list">
<div class="listing-item" data-price="20" data-duration="400" data-stops="3">Price 20, Duration 400, Stops 3</div>
<div class="listing-item" data-price="30" data-duration="350" data-stops="3">Price 30, Duration 350, Stops 3</div>
<div class="listing-item" data-price="10" data-duration="700" data-stops="2">Price 10, Duration 700, Stops 2</div>
<div class="listing-item" data-price="40" data-duration="500" data-stops="1">Price 40, Duration 500, Stops 1</div>
</div>
<button id="btnPrice" type="button">Sort by price</button>
<button id="btnDuration" type="button">Sort by duration</button>
<button id="btnBest" type="button">Sort by overall best</button>
最好的整体产品应该具有便宜的价格,持续时间短,并尽可能少停止。
我在考虑这种“矩阵计算”,将每个产品的每个因素与所有其他产品的相同属性进行比较。最后,我们将得到所有因子结果的总和。
e.g。
Product 1 has price of 20 and duration of 400 and stops = 3.
Product 2 has price of 30 and duration of 350 and stops = 3.
我会计算如下:
A
20/30 = 0.66
400/350 = 1.14
3/3 = 1
SUM = 1.8
乙
30/20 = 1.5
350/400 = 0.875
3/3 = 1
SUM = 2.375
在此计算产品中 A 获胜,因为所有因素的总和小于产品B的所有因子的总和。
迄今为止的理论。但我怎么能用JS ??
来实现这个目标答案 0 :(得分:0)
$("#btnBest").click(function () {
var Price = [];
var Duration = [];
var Stops = [];
divList.each(function() {
Price.push($(this).data('price'));
Duration.push($(this).data('duration'));
Stops.push($(this).data('stops'));
});
for(i=0; i< divList.length; i++) {
var PriceSum = 0;
var DurationSum = 0;
var StopsSum = 0;
var OverallSum = 0;
for(j=0; j < divList.length; j++) {
var newPriceSum = Price[i] / Price[j];
var newDurationSum = Duration[i] / Duration[j];
var newStopsSum = Stops[i] / Stops[j];
PriceSum = PriceSum + newPriceSum;
DurationSum = DurationSum + newDurationSum;
StopsSum = StopsSum + newStopsSum;
}
var OverallSum = PriceSum + DurationSum + StopsSum;
$(".listing-item" ).eq( i ).attr("data-sum", OverallSum);
//console.log(i + ": " + PriceSum + " + " + DurationSum + " + " + StopsSum + " = " + OverallSum);
}
divList.sort(function(a, b) {
return $(a).data("sum")-$(b).data("sum")
});
$("#list").append(divList);
});
如果感兴趣的话,请看小提琴。 https://jsfiddle.net/SchweizerSchoggi/k3af7pb0/