Last active
January 12, 2018 02:04
-
-
Save Woodsphreaker/6cf62e344813a340d36f83445c9ac3d3 to your computer and use it in GitHub Desktop.
Convert elements to array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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