首页 > 解决方案 > 我想找到最大的变化

问题描述

我的脚本不能只打印数据中的最后一个标记,我的脚本应该打印 zil,因为它是我数据中最大的变化

var olddata = 
[
    {"token": "NORD", "oldprice": 1},
    {"token": "DYP", "oldprice": 2.43},
    {"token": "ZIL", "oldprice": 0.20},
    {"token": "VET", "oldprice": 6.33}
]

var newdata = 
[
    {"token": "NORD", "newprice": 1.20},
    {"token": "DYP", "newprice": 2.80},
    {"token": "ZIL", "newprice": 0.40},
    {"token": "VET", "newprice": 6.90}
]
function findBiggestChange(oldData, newData) {
  var previousDifference = null;
  var changeIndex;
  oldData.forEach((obj, i) => {
    var data = newData.find(d => d.token === obj.token);
        var currentDifference = previousDifference ? Math.abs.forEach(data.newprice - obj.oldprice) : data.newprice;
        changeIndex = currentDifference > previousDifference ? i : 0;
  });
}

findBiggestChange(olddata,newdata);

标签: javascriptnode.jsarraysmathforeach

解决方案


我们可以使用Array.map创建一个变化列表,包括绝对(变化)和百分比(百分比变化)。

使用Array.sort,我们将按百分比变化的降序排序,以获得最大的百分比变化:

const olddata = [ {"token": "NORD", "oldprice": 1}, {"token": "DYP", "oldprice": 2.43}, {"token": "ZIL", "oldprice": 0.20}, {"token": "VET", "oldprice": 6.33} ]
const newdata = [ {"token": "NORD", "newprice": 1.20}, {"token": "DYP", "newprice": 2.80}, {"token": "ZIL", "newprice": 0.40}, {"token": "VET", "newprice": 6.90} ] 

// Get the percentage change and absolute change of each value...
const changes = olddata.map(({token, oldprice}, idx) => {
    const change = (newdata[idx].newprice - oldprice);
    const percentageChange = 100 * change / oldprice;
    return { token, percentageChange, change };
});

// Sort by percentage change, in descending order
const sortedByPercentChange = changes.sort((a, b) => b.percentageChange - a.percentageChange);

console.log("All changes (sorted on % change):", sortedByPercentChange)

// The largest change will be the first element...
console.log("Largest % change:", sortedByPercentChange[0])
   


推荐阅读