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

时间:2021-04-01 12:25:24

标签: javascript arrays

我是网站上的新手,我有一个非常简单的 JS 问题,但我无法解决。

我有一个字符串数组: 像这样:

guard let VC = self.navigationController?.viewControllers.filter({$0.isKind(of: YourViewController.self)}).first else {return}
self.navigationController?.popToViewController(VC, animated: true)

我想变成2个这样的数组:

arr = [
"Economic_Working",
"Health_Excursions",
"Health_Doctors",
"Health_Meditation",
"Social_Religion",
"Social_Holidays"
]
categoryArr = ["Economic" , "Health" , "Social" ];

第一个数组包含文本的第一部分, 在第二个数组中,我将第二部分放在第一个数组中,但根据其类别的索引

这就是我尝试做的:

subCategoryArr = [
["Working"] ,
[ "Meditation" , "Doctors" , "Excursions"] ,
[ "Religion" , "Holidays"]
 ];

3 个答案:

答案 0 :(得分:2)

您可以 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" ]
}

答案 1 :(得分:0)

您可以使用 javascript 集来确保没有重复的条目。你的代码会是这样的

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

let convertTo2Arrays = (array) => {
  let categorySet = new Set();
  let subCategorySet = new Set();
  array.forEach(item => {
   let firstPart = item.split("_")[0];
   let secondPart = item.split("_")[1];
   categorySet.add(firstPart);
   subCategorySet.add(secondPart);
  })
  return {
    categories: Array.from(categorySet),
    subCategories: Array.from(subCategorySet)
  }
}

console.log(convertTo2Arrays(arr))

答案 2 :(得分:-1)

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

function returnParts(arr){
  let firstParts = [];
  let lastParts = [];
  arr.forEach(elem=>{
    let [firstPart, lastPart] = elem.split("_"); // destructure to get firstPart and lastPart
    
    // push only if it doesn't already exists

    if(!firstParts.includes(firstPart)){
      firstParts.push(firstPart);
    }  
    if(!lastParts.includes(lastPart)){
      lastParts.push(lastPart);
    }
  });
  return [firstParts, lastParts];
}

const [firstParts, lastParts] = returnParts(arr);

console.log(firstParts)
console.log(lastParts)