Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Last active January 12, 2018 02:04
Show Gist options
  • Save Woodsphreaker/6cf62e344813a340d36f83445c9ac3d3 to your computer and use it in GitHub Desktop.
Save Woodsphreaker/6cf62e344813a340d36f83445c9ac3d3 to your computer and use it in GitHub Desktop.
Convert elements to array
const arr = [
{
id: 10,
title: "Test 10",
item: "Item 1"
},
{
id: 10,
title: "Test 10",
item: "Item 2"
},
{
id: 10,
title: "Test 10",
item: "Item 2"
},
{
id: 11,
title: "Test 11",
item: "Item 1"
},
{
id: 11,
title: "Test 11",
item: "Item 2"
},
{
id: 11,
title: "Test 11",
item: "Item 3"
},
{
id: 11,
title: "Test 11",
item: "Item 3"
},
{
id: 11,
title: "Test 11",
item: "Item 4"
},
]
const flatten = (acc, el) => {
const element = acc.find(f => f.id === el.id)
element
? element.itens = [...new Set(element.itens.concat(el.item))]
: acc.push({
id: el.id,
title: el.title,
itens: [el.item]
})
return acc
}
const convertArr = arr => arr.reduce((flatten), [])
console.log(convertArr(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment