Last active
May 4, 2022 10:12
-
-
Save perian/2f4286f9d098af285491380588a3f1af to your computer and use it in GitHub Desktop.
Hash Table #1
This file contains 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
const groupBy = (array, prop) => { | |
const obj = {}; | |
for (let el of array) { | |
// el[prop] in obj проверяеть еще и prototype | |
// Object.prototype.hasOwnProperty.call(obj, 'key') вот самый safe вариант | |
// if Array.isArray(obj[key]) как вариант | |
if (!(obj.hasOwnProperty(el[prop]))) { | |
obj[el[prop]] = []; | |
} | |
obj[el[prop]].push(el); | |
} | |
return obj; | |
}; | |
console.log( | |
groupBy( | |
[ | |
{ id: 1, universe: "marvel", name: "Hulk" }, | |
{ id: 2, universe: "marvel", name: "Iron Man" }, | |
{ id: 3, universe: "dc", name: "Aqua Man" }, | |
{ id: 4, universe: "dc", name: "Bat Man" }, | |
{ id: 5, universe: "marvel", name: "Hulk" } | |
], | |
"universe" | |
) | |
); | |
// OUTPUT | |
// => { | |
// marvel: [ | |
// { id: 1, universe: "marvel", name: "Spider Man"}, | |
// { id: 2, universe: "marvel", name: "Iron Man"}, | |
// { id: 5, universe: "marvel", name: "Hulk"}, | |
// ], | |
// dc: [ | |
// { id: 3, universe: "dc", name: "Aqua Man"}, | |
// { id: 4, universe: "dc", name: "Bat Man"}, | |
// ] | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment