Presented below is a solution that does not rely on external libraries:
/**
* Function to add an object to a set.
*
* @param {object} theSet The set where the object will be added.
* @param {object} theObject The object to be added.
*
* @return {object} theSet with theObject added.
*
* @note Assumes that theObject.name is the key,
* and theObject.id should be in the value array.
* @note This operates as a callback for Array.prototype.reduce().
*/
function collect(theSet, theObject) {
if (theSet.hasOwnProperty(theObject.name)) {
theSet[theObject.name].push(theObject.id);
} else {
theSet[theObject.name] = [theObject.id];
}
return theSet;
}
var names = [{name:"high",id:5},{name:"high",id:6},
{name:"low",id:1}, {name:"low",id:2},{name:"medium",id:3},{name:"medium",id:4}],
combinedSet = names.reduce(collect, {}), // Step 1
final = [],
key;
// Step 2
for (key in combinedSet) {
if (combinedSet.hasOwnProperty(key)) {
final.push(
{
"name" : key,
"items": combinedSet[key]
}
);
}
}
The initial step involves organizing the IDs under their respective object names. This is achieved using Array.prototype.reduce
with the callback function collect
. The outcome of this process is stored in the combinedSet
variable.
In the subsequent step, we convert the set created in Step 1 into the final array, creating objects wherein the keys from the set are assigned to the name
attribute and the values are assigned to the items
attribute. Since reduce
cannot be used here as before, a basic for
loop is employed. It's worth noting the inclusion of hasOwnProperty
check to mitigate potential issues arising from modifications made to Object.prototype
; without this safeguard, unintended items could appear in the set, leading to errors.