我有這個二維陣列
var data = [
['12-9', 134],
['12-9', 148],
['12-9', 92],
['1-8', 116],
['1-8', 136],
['1-8', 150],
['21-5', 138],
['21-5', 143],
['21-5', 119],
['21-5', 125]
]
如果一個專案的第一個值與其他一個值匹配,我想計算第二個的平均值。
例如:前 3 個元素都有“12-9”,為此它應該給我 124,7,因為 (137 148 92) / 3 = 124,7。
這可能很容易,但我被卡住了。我用 map() 和 reduce() 或 filter() 嘗試過,但對我沒有任何作用。我很確定我不會在這里看到明顯的東西。
現在我再次傾倒所有東西,這是我現在的新起點:
for (let item of data) {
var temp = item[0];
var myValues = data.filter((value) => {
return value[0] === temp;
});
console.log(myValues );
}
uj5u.com熱心網友回復:
過濾和減少是您所需要的
const data = [['12-9', 134],['12-9', 148],['12-9', 92],['1-8', 116],['1-8', 136],['1-8', 150],['21-5', 138],['21-5', 143],['21-5', 119],['21-5', 125]];
const avg = data.reduce((acc, item) => {
const key = item[0]
if (!acc[key]) {
const same = data
.filter(nums => nums[0] === key);
acc[key] = {
count: same.length,
avg: (same.reduce((acc, [key, num]) => acc num, 0) / same.length).toFixed(2) // key is ignored we could use an underscore to show that
}
}
return acc
}, {})
console.log(avg)
uj5u.com熱心網友回復:
下面是一個示例,它縮減為按第一個元素分組的 Map,然后迭代結果以平均分組陣列并重建原始陣列的形狀。
const data = [['12-9', 134], ['12-9', 148], ['12-9', 92], ['1-8', 116], ['1-8', 136], ['1-8', 150], ['21-5', 138], ['21-5', 143], ['21-5', 119], ['21-5', 125],];
const map = data.reduce((a, [k, v]) => a.set(k, [...(a.get(k) ?? []), v]), new Map());
const result = [...map.entries()].map(([k, vs]) => [k, vs.reduce((a, b) => a b) / vs.length]);
console.log(result);
或者在連續for...of回圈中應用類似的邏輯,但這次跟蹤每個元素的運行總和和計數,從而避免后來減少計算平均值。
const data = [['12-9', 134], ['12-9', 148], ['12-9', 92], ['1-8', 116], ['1-8', 136], ['1-8', 150], ['21-5', 138], ['21-5', 143], ['21-5', 119], ['21-5', 125],];
const map = new Map();
for (const [key, value] of data) {
if (!map.has(key)) {
map.set(key, { sum: 0, count: 0 });
}
map.get(key).count = 1;
map.get(key).sum = value;
}
const result = [];
for (const [key, { sum, count }] of map) {
result.push([key, sum / count]);
}
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355929.html
標籤:javascript 数组
