0

whats the best way to convert an array of strings and group them together into objects if they have same substring,

  const parameters = ["product_groups", "product_filters", "location_groups"];

  const desiredOutput = [
    { product: ["product_groups", "product_filters"] },
    { location: ["location_groups"] }
  ];

Tried using the map method, however having problems grouping them and putting multiple values into the same array.

  const desiredOutput = parameters.map(value => {
    return {
      [value]: value
    };
  });
1
  • Please add your map code Commented Dec 29, 2022 at 8:22

2 Answers 2

0

Or, in ES6 style, you can do this:

const parameters = ["product_groups", "product_filters", "location_groups"];

const res=Object.entries(parameters.reduce((a,c)=>
 ((a[c.replace(/_.*/,"")]??=[]).push(c),a)
,{})).map(([k,v])=>({[k]:v}))

console.log(res)

Sign up to request clarification or add additional context in comments.

Comments

0

you could do something like this:

const parameters = ["product_groups", "product_filters", "location_groups"];

function groupTogether(arr) {
    const groups = {}
    
    for (let i = 0; i < arr.length; i++) {
        const parameter = arr[i];
        const [group] = parameter.split('_')
        if (!groups[group]) groups[group] = [parameter]
        else groups[group].push(parameter)
    }
    
    return Object.entries(groups).map(([group, value]) => ({
        [group]: value
    }))
}

console.log(groupTogether(parameters));

//[
//  { product: [ 'product_groups', 'product_filters' ] },
//  { location: [ 'location_groups' ] }
//]

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.