Skip to content

Instantly share code, notes, and snippets.

@perian
Last active May 4, 2022 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perian/2f4286f9d098af285491380588a3f1af to your computer and use it in GitHub Desktop.
Save perian/2f4286f9d098af285491380588a3f1af to your computer and use it in GitHub Desktop.
Hash Table #1
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