我正在开发一个涉及嵌套数组的项目,我需要按大小对每个数组中的 1 个值进行排序。 (所有数组都采用相同的格式,例如 [a,b,c,d])。
为了更清楚地说明,我如何从像 time[60][x]
这样的数组中选择更大的数字,其中 x 是数组的数量(这是一个非常奇怪的嵌套)。
const time = {
15: [
{ language: 'english', raw: 105.6, acc: 93.94, wpm: 96, punctuation: false }
],
30: [
{ language: 'english', raw: 66.4, wpm: 66.4, punctuation: false, difficulty: 'normal' }
],
60: [
{ acc: 98.97, language: 'english', puncutation: false, wpm: 96, difficulty: 'normal' },
{ acc: 92.63, puncutation: false, language: 'english_10k', wpm: 59.19, raw: 60.99 }
]
};
如您所见,每个数组中嵌套了不同数量的数组,例如 time[60][2]
其中有 2 个数组。
这就是对象的结构。我需要从每个数组的 wpm 列中找到最大值。
非常感谢任何和所有的帮助,
谢谢
最佳答案
如果我正确理解您的问题,这可能就是您所需要的:
const time = {
15: [{wpm: 10}, {wpm: 15}, {wpm: 20}],
30: [{wpm: 5}, {wpm: 10}, {wpm: 30},],
60: [{wpm: 4}, {wpm: 12}, {wpm: 8},]
};
const results = {};
// iterate over the time object
for (let key in time) {
results[key] = time[key].reduce((acc, item) => {
if (item.wpm > acc) {
return item.wpm;
}
return acc;
}, 0);
}
console.log(results);
关于javascript - 如何比较多个数组中的相同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63853448/