猿问

JS:根据列表的最后一个元素计算节省量

我列出了价格:

 prices =  [57, 69, 90, 108, 142, 216, 344, 459, 670, 1134]

我需要根据最后一个计算当前元素的节省。

savings = [39, 61, 68, 75, 81, 85, 87, 88, 90] #first element should be empty or dropped, as first element or **prices** doesn't have something to calculate savings on.

看到具有确切值的图像:

注意:我可以计算其他指标,例如平均值等。但是无法想到一种使用地图或基于列表中最后一项进行计算的方法。


   var sum = prices.reduce(function (sum, value) {

          return sum + value;

        }, 0);


   alert("SUM: " + sum);


   var avg = sum / prices.length;


   alert("AVG: " + avg);


   var diffs = prices.map(function (value) {

            var diff = value - avg;

            return diff;

   });


   alert(diffs);


米脂
浏览 133回答 2
2回答

白猪掌柜的

节省额是根据第一个项目的成本与其他项目的单位成本进行比较得出的。所以percentage of savings = (1 - UnitCost / BaseUnitCost) * 100因此,使用map来计算保存量,因为它是基本单位,所以跳过了第一个索引。var prices = [57, 69, 90, 108, 142, 216, 344, 459, 670, 1134]var quantity = [50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000]var min = prices[0]/quantity[0]var savings = prices.map((v, i) => i ? `Save ${Math.round((1-(v/quantity[i])/min)*100)}%` : '')console.log(savings)

守着星空守着你

您要首先根据数量和价格计算单位成本,然后从初始单位成本中计算出节省额:function calcUnitCosts(quantities, prices){&nbsp; &nbsp; if( quantities.length != prices.length ) throw 'Array sizes unequal';&nbsp; &nbsp; var unitCosts = [];&nbsp; &nbsp; for( var i = 0; i < prices.length; i++ ){&nbsp; &nbsp; &nbsp; &nbsp;unitCosts.push(prices[i] / quantities[i]);&nbsp; &nbsp; }&nbsp; &nbsp; return unitCosts;}function calcCostSavings(baseUnitCost, remainingUnitCosts){&nbsp; &nbsp; var costSavings = [];&nbsp; &nbsp; remainingUnitCosts.forEach((unitCost) => {&nbsp; &nbsp; &nbsp; &nbsp; costSavings.push((baseUnitCost - unitCost)/baseUnitCost)&nbsp; &nbsp; })&nbsp; &nbsp; return costSavings;}costSavings = calcCostSavings(unitCosts[0], unitCosts.slice(1))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答