【发布时间】:2021-07-20 13:24:36
【问题描述】:
我有返回单个 int 值的 JSON 数据。经过一些更改,这些值现在以整数数组(以及原始格式)的形式返回。
{
"value": 10,
"value": 70,
"value": 30,
"value": 200
}
- and -
{
"value": [64, 13, 55, 34, 52, 43, 59, 20, 20],
"value": [10, 90, 20, 80, 30, 70, 60, 40, 50]
}
我有一个公式可以返回旧版本 JSON 数据的最小值、最大值和总和。现在它不起作用,我不知道重写函数来处理数组的最佳方法是什么。或者如果创建第二个函数来处理数组并检查它是 int 还是数组更好?
有没有办法返回(从上面的数字):
// no value array, apply to all
[ 10, 200, 310 ] // min, max, sum
- and -
// for each of the value arrays
[ 23, 64, 360 ] // val 1 - min, max, sum
[ 10, 90, 450 ] // val 2 - min, max, sum
// input data
const value = document.querySelectorAll( "div" ).forEach( el => {
const contents = el.textContent, // get the text in the <div>
json = JSON.parse( contents ), // parse the data
jsonData = json.data; // get the data only
// normalise the data
// @from: https://stackoverflow.com/a/67294607/1086990
const normaliseData = arr => {
const data = arr.map(({ value }) => value);
return typeof arr[0].value === 'number' ? [data] : data;
};
// add into const
const valueArray = normaliseData( jsonData );
// get the min / max / sum
const minMaxSum = valueArray.forEach( e => {
return [
Math.min(...e),
Math.max(...e),
[...e].reduce((v, w) => v + w)
];
});
// output
console.log( minMaxSum );
});
<div>
{ "data": [ { "value": [64, 23, 45, 34, 52, 43, 59, 40] }, { "value": [10, 90, 20, 80, 30, 70, 60, 40, 50] } ] }
</div>
<div>
{ "data": [ { "value": 600 }, { "value": 70 }, { "value": 30 } ] }
</div>
【问题讨论】:
-
我猜你迷路了,因为你使用
reduce里面有 20 行内容,而简单的 3 行循环也可以解决问题。 -
@georg 你如何将它简化为 3 行?
标签: javascript arrays