我试图找出是否有一种方法可以使用array.map()
我有两个位置列表(WOL,SYD,MEL等),其中一个具有每个站点中所有设备作为子设备的站点总数,另一个具有仅错误的设备。
我需要找到每个站点的设备错误百分比,而不是每个站点的设备总数。
有没有办法我可以使用uniqueSitesCount.map(...)?整个周末,我一直在浏览文档,并尝试在此处提出要求之前先弄清楚,但到目前为止失败了。uniqueSitesCountNotOk
-仅将处于错误状态的设备添加到“设备”子数组的位置数组:
[ { site: 'CBR',
devices: [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'MEL',
devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'SYD', devices: [] },
{ site: 'WOL', devices: [] } ]
uniqueSitesCount
-包含所有对象的位置的数组[ { site: 'CBR',
devices: [ [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'MEL',
devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'SYD', devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'WOL', devices: [ [Object], [Object], [Object], [Object], [Object] ] } ]
功能:
编辑:
uniqueSitesCount[i].count
到uniqueSitesCount[i].devices.length
为清楚起见var getSiteErrorPercentage = function(uniqueSitesCount, uniqueSitesCountNotOk) {
for (var i = 0; i < uniqueSitesCount.length; i++) {
if (uniqueSitesCountNotOk[i].devices.length > 0) {
console.log(`${uniqueSitesCount[i].site} - ${(uniqueSitesCountNotOk[i].devices.length / uniqueSitesCount[i].devices.length* 100).toFixed(2)}%`)
} else {
console.log(uniqueSitesCount[i].site + ' - 0%')
}
}
}
最佳答案
我会考虑快速遍历uniqueSitesCount
以使对象直接将站点映射到对象数。就像是:
var uniqueSitesCount = [
{ site: 'CBR', devices: [[],[],[],[],[],[],[],[],[],[],[] ] },
{ site: 'MEL', devices: [[],[],[],[],[] ] },
{ site: 'SYD', devices: [[],[],[],[],[] ] },
{ site: 'WOL', devices: [[],[],[],[],[] ] }
]
var counts = uniqueSitesCount.reduce((acc, cur) => {
acc[cur.site] = cur.devices.length
return acc
}, {})
计数看起来像:
{ CBR: 11, MEL: 5, SYD: 5, WOL: 5 }
有了它,您可以映射错误并创建一个百分比如下的数组:
var uniqueSitesCount = [
{ site: 'CBR', devices: [[],[],[],[],[],[],[],[],[],[],[] ] },
{ site: 'MEL', devices: [[],[],[],[],[] ] },
{ site: 'SYD', devices: [[],[],[],[],[] ] },
{ site: 'WOL', devices: [[],[],[],[],[] ] }
]
var uniqueSitesCountNotOk = [
{ site: 'CBR', devices: [ [], [], [], [], [], [] ] },
{ site: 'MEL', devices: [ [], [], [], [], [] ] },
{ site: 'SYD', devices: [] },
{ site: 'WOL', devices: [] }
]
var counts = uniqueSitesCount.reduce((acc, cur) => {
acc[cur.site] = cur.devices.length
return acc
}, {})
var percents = uniqueSitesCountNotOk.map(item => {
var n = item.devices.length / counts[item.site] * 100
return {site:item.site, count: n}
})
console.log(percents)
另外,您可以避免使用count对象,但是每次都必须搜索
uniqueSitesCount
对象:var percents = uniqueSitesCountNotOk.map(item => {
var site = uniqueSitesCount.find(i => i.site === item.site )
var n = item.devices.length / site.devices.length * 100
return {site:item.site, count: n}
})