Created
August 24, 2022 17:16
-
-
Save christopherwxyz/d070a090d621010b21483da9040fabe6 to your computer and use it in GitHub Desktop.
groupingDishes
This file contains hidden or 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
function solution(dishes) { | |
let dishMap = {}; | |
let ingredientsMap = {}; | |
dishes.forEach((_, i) => { | |
dishMap[dishes[i][0]] = new Set(dishes[i].slice(1)); | |
}); | |
[...new Set(dishes.map((x) => x.slice(1)).flatMap((x) => x))].map((x) => { | |
for (const key in dishMap) { | |
if (dishMap[key].has(x)) { | |
if (ingredientsMap[x] === undefined) ingredientsMap[x] = []; | |
ingredientsMap[x].push(key); | |
} | |
} | |
}); | |
return Object.entries(ingredientsMap) | |
.filter(([key, value]) => { | |
if (value.length >= 2) { | |
return [key, value.sort()]; | |
} | |
}) | |
.sort((a, b) => { | |
if (a[0] < b[0]) return -1; | |
if (a[0] > b[0]) return 1; | |
return 0; | |
}) | |
.map((x) => x.flat()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My answer for CodeSignal where: