Convert an array of strings, into 2 arrays of categories and subcategories

Viewed 105

I'm new here on the site, I have a very simple problem with JS, but I'm unable to resolve it.

I have an array of strings: something like this:

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

I want to become 2 such arrays:

categoryArr = ["Economic" , "Health" , "Social" ];
subCategoryArr = [
["Working"] ,
[ "Meditation" , "Doctors" , "Excursions"] ,
[ "Religion" , "Holidays"]
 ];

The first array contains the first part of the text, And in the second array, I put the second part but according to the index which is of its category which is in the first array

this is what i try to do:

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))

2 Answers

You could reduce the array and create an accumulator object which maps each category to the subcategory array. Then, get the keys and values of that object

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) )

The object returned by reduce:

{
  "Economic": [ "Working" ],
  "Health": [ "Excursions", "Doctors", "Meditation" ],
  "Social": [ "Religion", "Holidays" ]
}

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)

Related