gpt4 book ai didi

javascript - 在javascript中查找嵌套对象数组中的百分比值

转载 作者:行者123 更新时间:2023-12-02 22:57:06 26 4
gpt4 key购买 nike

在数组的嵌套对象中,百分比值应映射到具有更大计数的对象。数据对象有两个数组 "distinctCount""groupByAndCount" 。uniqueCount 包含一个对象。

     {
"key": "total",
"value": 7
}

基于键名的“groupByAndCount”对象应该被分组,并且应该获取具有最高计数的值并除以“distinctCount”中获得的值并乘以100以获得百分比例子:在键“marital_status”中,与值“已婚”相比,“单例”值的计数最高“6”具有低计数的strong>“1”

       {
"key": "marital_status",
"value": "Single",
"count": 6/7*100 = 85.7%
}

我是reduce函数的初学者,我认为reducer函数需要用百分比来获取缩减的对象

const result = data.groupByAndCount.map(e => e.reduce((a, { key, value, count }) => 
(a['key'] = key,a['value'] = value,a['count'] = count, a), {}));
const data = {
distinctCount : [
{
"key": "total",
"value": 7
},
{
"key": "member_total",
"value": 7
}
]
,
groupByAndCount : [
[
{
"key": "marital_status",
"value": "Married",
"count": 1
},
{
"key": "marital_status",
"value": "Single",
"count": 6
}
],
[
{
"key": "payment",
"value": "POST",
"count": 7
}
],
[
{
"key": "customer_code",
"value": "ABC",
"count": 1
},
{
"key": "customer_code",
"value": "DEF",
"count": 6
}
]
]
};

预期结果:

const result = {
distinctCount : [
{
"key": "total",
"value": 7
},
{
"key": "member_total",
"value": 7
}
]
,
groupByAndCount : [
[
{
"key": "marital_status",
"value": "Single",
"count": 85.71
}
],
[
{
"key": "payment",
"value": "POST",
"count": 100
}
],
[
{
"key": "customer_code",
"value": "DEF",
"count": 85.71
}
]
]
};

最佳答案

首先,您的总计数是唯一的,因此您可以将其取出到变量中以方便计算。您可以通过对对象数组进行简单搜索来实现这一点 (data.distinctCount)。

function search(array, value){
for (var i=0; i < array.length; i++) {
if (array[i].key === value) {
return array[i].value;
}
}
}

const total_value = search(data.distinctCount, 'total');

Output:
7

其次,您只需要每个数组中具有最大计数的对象(data.groupByAndCount 内的数组)。

const maxGroupByAndCount = data.groupByAndCount.map(function(arr){
return [arr.sort((a,b)=>b.count-a.count)[0]];
});

Output:
[
[{key: "marital_status", value: "Single", count: 6}],
[{key: "payment", value: "POST", count: 7}],
[{key: "customer_code", value: "DEF", count: 6}]
]

现在,只需与 total_value 进行比较,即可将每个计数转换为百分比;

maxGroupByAndCount.map(function(arr){
arr[0].count = (arr[0].count/ total_value) * 100;
});

console.log(maxGroupByAndCount);

Output:
[
[{key: "marital_status", value: "Single", count: 85.71428571428571}],
[{key: "payment", value: "POST", count: 100}],
[{key: "customer_code", value: "DEF", count: 85.71428571428571}]
]

现在您可以进行对象分配以使其成为一个。

const result = { 
'distinctCount' : data.distinctCount,
'groupByAndCount': maxGroupByAndCount
};

您绝对可以改进我的答案,使其更加优化。

关于javascript - 在javascript中查找嵌套对象数组中的百分比值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com