0

I have an array with prefix values

["options_a",
"options_b",
"options_c",
"capable_d",
"capable_e_c"
]

i need the output to be in object format with prefix as key and grouped split string as value

object output format needed
{
"options":["a","b","c"],
"capable":["d","e_c"]
}

it can be done with normal for loop, but is there better way of achieving it with simplified form using es6 functionality.

Thank you.

Lohith
  • 866
  • 1
  • 9
  • 25

1 Answers1

2

Reduce the array of the prefixed values. Split the item by underscore (_), and use destructuring to get the key, and an array of value (the value might have multiple items after splitting by underscore). If the accumulator (acc) doesn't contain the key, create one with an empty array. Push the value to acc[key] after joining it by underscore.

const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"]

const result = arr.reduce((acc, item) => {
  const [key, ...value] = item.split('_')
  
  if(!acc[key]) acc[key] = []
  
  acc[key].push(value.join('_'))

  return acc;
}, {})

console.log(result)

You can avoid the need to join by using a RegExp to split only by the 1st underscore (see this answer):

const arr = ["options_a","options_b","options_c","capable_d","capable_e_c"]

const result = arr.reduce((acc, item) => {
  const [key, value] = item.split(/_(.+)/)
  
  if(!acc[key]) acc[key] = []
  
  acc[key].push(value)

  return acc;
}, {})

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Both answers looks great, but which one would be the better one to choose if the data gets big, for me it seems to be your second answer without join. – Lohith Nov 07 '20 at 13:01
  • 1
    It's probably the 2nd, due to a temp array that would be garbage collected in the 1st one. You can always profile it, and see which is faster. – Ori Drori Nov 07 '20 at 13:05