javascript - 我想找到最大的变化
问题描述
我的脚本不能只打印数据中的最后一个标记,我的脚本应该打印 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);
解决方案
我们可以使用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])
推荐阅读
- javascript - 当我尝试在 JavaScript 中将十六进制字符串转换为整数时,我得到的数字与在 python 中的数字不同
- android - 使用 Volley 库的 JSON 数组请求解析错误
- arrays - 如何从 Google 表格中的范围动态构建数组?
- python-3.x - 在 Python3 的类中动态装饰一个函数
- html - 代码帮助!我想覆盖一个部分的背景和悬停颜色
- angular - 在“路径”中键入“名称”是 2 个模块声明的一部分:构建 Ionic 4 项目时出错
- python - 更改数据框的列名后出现键错误
- neural-network - 用python重置神经网络中的连接
- javascript - 如何使用 mongoose 更新 mongodb 中的值?
- c++ - 由于二维数组声明,C++ 14 中的运行时错误