Iterate over an array and create a new sorted object.

I'm completely brain farting. I have data coming in like
const data = [
{
name: "Eggs",
category: "Groceries",
},
{
name: "Meat",
category: "Groceries",
},
{
name: "Screwdriver",
category: "Tools",
},
...
]
const data = [
{
name: "Eggs",
category: "Groceries",
},
{
name: "Meat",
category: "Groceries",
},
{
name: "Screwdriver",
category: "Tools",
},
...
]
and I need to sort them to create an object with this shape:
const newShape = [
{
category: "Groceries",
options: [
...all the objects from the input array with the category "Groceries",
{
name: "Eggs",
value: 'eggs'
}
]
},
{
category: "Tools",
options: [
...all the objects from the input array with the category "Fools",
{
name: "Screwdriver",
value: "screwdriver"
}
]
},
...etc for each unique category value
]
const newShape = [
{
category: "Groceries",
options: [
...all the objects from the input array with the category "Groceries",
{
name: "Eggs",
value: 'eggs'
}
]
},
{
category: "Tools",
options: [
...all the objects from the input array with the category "Fools",
{
name: "Screwdriver",
value: "screwdriver"
}
]
},
...etc for each unique category value
]
And I'm struggling to think of an elegant way to do this. Any suggestions?
6 Replies
Vincent Udén
Vincent Udén2y ago
Array.prototype.group() - JavaScript | MDN
The group() method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group.
Vincent Udén
Vincent Udén2y ago
Basically does what you want
Donny D
Donny D2y ago
yeah but that's still experimental
Vincent Udén
Vincent Udén2y ago
Oh mb, although it is easy to find an implementation of this one using reduce which could be considered elegant
Donny D
Donny D2y ago
I came up with this
const categories = [...new Set(data.map((data) => data.category))];

return categories.map((category) => {
const dataByCategory = _.partition(data, (a) => a.category === category);

return {
label: category,
options: dataByCategory[0].map((a) => {
return {
label: data.name,
value: data.name
}
}
});
const categories = [...new Set(data.map((data) => data.category))];

return categories.map((category) => {
const dataByCategory = _.partition(data, (a) => a.category === category);

return {
label: category,
options: dataByCategory[0].map((a) => {
return {
label: data.name,
value: data.name
}
}
});
Vincent Udén
Vincent Udén2y ago
Looks good 👍
Want results from more Discord servers?
Add your server