Given the following values:
const values = ['name1|engine1|color1', 'name2|engine2|color2', 'name3|engine3|color3']
I would like to create an array for the values of the same position, like this:
cars = {
names: ['name1', 'name2', 'name3'],
engines: ['engine1', 'engine2', 'engine3'],
colors: ['color1', 'color2', 'color3'],
...other properties
}
I tried to do it this way:
values.reduce((acc, value) => {
const [name, engine, color] = value.split('|')
acc.names.push(name)
acc.engines.push(engine)
acc.colors.push(color)
return acc
}, {})
The problem is that acc.name, acc.engine and acc.color don't exist yet, and it gives an error on push. What would be a way to do this cleanly, taking into account that they will have other properties?
{}, use{ names: [], engines: [], colors: []}instead(acc.names ??= []).push(name). This is most useful when the keys aren't known in advance or are derived from the reduced elements.