gpt4 book ai didi

javascript - 将字符串数组转换为 2 个类别和子类别数组

转载 作者:行者123 更新时间:2023-12-04 03:35:56 28 4
gpt4 key购买 nike

我是网站上的新手,我有一个非常简单的 JS 问题,但我无法解决。
我有一个字符串数组:
像这样:

arr = [
"Economic_Working",
"Health_Excursions",
"Health_Doctors",
"Health_Meditation",
"Social_Religion",
"Social_Holidays"
]
我想成为 2 个这样的数组:
categoryArr = ["Economic" , "Health" , "Social" ];
subCategoryArr = [
["Working"] ,
[ "Meditation" , "Doctors" , "Excursions"] ,
[ "Religion" , "Holidays"]
];

第一个数组包含文本的第一部分,
在第二个数组中,我放置了第二部分,但根据第一个数组中属于其类别的索引
这就是我尝试做的:

let arr = [
"Economic_Working",
"Health_Excursions",
"Health_Doctors",
"Health_Meditation",
"Social_Religion",
"Social_Holidays"
]

let convertTo2Arrays = (array) => {
let categoryArr = []
array.map(item => {
firstPart = item.split("_")[0];
return categoryArr.push(firstPart)
})

return categoryArr;
}

console.log(convertTo2Arrays(arr))

最佳答案

您可以 reduce 数组并创建一个累加器对象,该对象将每个类别映射到子类别数组。然后,获取该对象的键和值

const arr = ["Economic_Working", "Health_Excursions", "Health_Doctors", "Health_Meditation", "Social_Religion", "Social_Holidays"];

const group = arr.reduce((acc, str) => {
const [cat, subCat] = str.split('_');
acc[cat] = acc[cat] || []
acc[cat].push(subCat)
return acc
}, {})

console.log( Object.keys(group) )
console.log( Object.values(group) )
reduce 返回的对象:
{
"Economic": [ "Working" ],
"Health": [ "Excursions", "Doctors", "Meditation" ],
"Social": [ "Religion", "Holidays" ]
}

关于javascript - 将字符串数组转换为 2 个类别和子类别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66904450/

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