Skip to content

Instantly share code, notes, and snippets.

@DreadBoy
Created July 27, 2019 22:16
Show Gist options
  • Save DreadBoy/fb85aa05de83d738a896fc2440acbf66 to your computer and use it in GitHub Desktop.
Save DreadBoy/fb85aa05de83d738a896fc2440acbf66 to your computer and use it in GitHub Desktop.
// Write a function (in any language) that accepts an array of objects each containing a product name and list of locations (e.g. [“Paris”, “France”, “Europe”]), and returns an array of location objects with a list of names associated with each location. Paste a link to a private gist (gist.github.com) here.
type Product = {
name: string,
locations: string[],
};
const products: Product[] = [{name: 'France', locations: ['Paris', 'Chamonix']}]
function groupByLocation(products: Product[]) {
const groups: {[location: string]: string[]} = {};
products.forEach(product => {
product.locations.forEach(location => {
if(!(location in groups))
groups[location] = [];
if(!groups[location].includes(product.name)
groups[location].push(product.name);
}
}
return groups;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment