Skip to content

Instantly share code, notes, and snippets.

@celestelayne
Last active June 18, 2022 16:14
Show Gist options
  • Save celestelayne/74cbaf74d55ba4985bc470313fc6147e to your computer and use it in GitHub Desktop.
Save celestelayne/74cbaf74d55ba4985bc470313fc6147e to your computer and use it in GitHub Desktop.
Process the input & print out in the console an output where people are grouped by the same color they have.
/*
We need you to process the above input & print out in the console an output where people are grouped by the same color they have.
Assumptions:
- Group1: is an object inside another object, groups
- John: is a property of the object, Group1
*/
const groups = {
Group1: {
John: "Blue",
Peter: "Green"
},
Group2: {
Jane: "Red",
May: "Green"
},
Group3: {
Howard: "Blue",
Nguyen: "Red",
Lim: "Green"
}
};
const processNamesByColor = (data) => {
let group, value, group_name, result = {}, newgroup = {}
for(let key in data) {
group_name = key; // Group 1
group = data[key] // {Howard: 'Blue', Nguyen: 'Red', Lim: 'Green'}
// iterate over each object
for(let property in group){
value = Object.values(group) // [ 'Blue', 'Green' ]
result[property] = group[property]
}
newgroup[group_name] = []
}
let sorted_by_color = Object.entries(result).sort((a, b) => a[1].localeCompare(b[1])).map(el=>el)
let group_split_by_color = sorted_by_color.filter(function(color) {
let array_to_object = color.reduce(function(obj, val) {
obj[val] = color[1];
return obj;
}, {})
if(color[1] === 'Green'){
newgroup['Group1'] = array_to_object
} else if (color[1] === 'Blue'){
newgroup['Group2'] = array_to_object
} else if (color[1] === 'Red'){
newgroup['Group3'] = array_to_object
}
})
console.log(newgroup);
return newgroup
}
console.log(processNamesByColor(groups));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment