As a starting point, I have split the problem into two.
First merging the workId
’s. For this I have used an object. We loop through the original collection and look to see if the target object (mergedObjCollection) has a key name matching the artist name. If not, we create a key of artist name and assign an empty array. We then push the workid
to that array.
const collection = [
{
"artistName": "NgaNguyen Duy",
"workId": "554a9e4fa36f794b31000024"
},
...
]
const mergedObjCollection = {}
for (let {artistName, workId} of collection) {
if (!mergedObjCollection[artistName]) {
mergedObjCollection[artistName] = []
}
mergedObjCollection[artistName].push(workId)
}
Output:
{
Kristin: ['557a4kfbcc5e2a7110000223'],
NgaNguyen Duy: (2) ['554a9e4fa36f794b31000024', '554d3ffbcc477a7110000003']
}
We can now convert that back to their respective objects.
const mergedCollection = []
for (let [artistName, workId] of Object.entries(mergedObjCollection)) {
mergedCollection.push({artistName, workId})
}
Output:
[
{
artistName: "NgaNguyen Duy",
workId: (2) ['554a9e4fa36f794b31000024', '554d3ffbcc477a7110000003']
},
{
artistName: "Kristin",
workId: ['557a4kfbcc5e2a7110000223']
}
]
The following links maybe useful reading
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well...
Destructuring Assignment
Edit: The above combined into a function
function mergeWorkIds(collection) {
const mergedWorkIds = {}
for (let {artistName, workId} of collection) {
if (!mergedWorkIds[artistName]) mergedWorkIds[artistName] = []
mergedWorkIds[artistName].push(workId)
}
return Object
.entries(mergedWorkIds)
.map(([artistName, workId]) => ({artistName, workId}))
}