JSFiddle - React, Tailwind, and code Playground
by Ico Dimchev
HTML
<h1>View Console</h1>
JavaScript
function Person(firstName, lastName, age)
{
return {
firstName: String(firstName) || '',
lastName : String(lastName) || '',
age : parseInt(age) || 0,
toString : (function()
{
return this.firstName + ' ' + this.lastName + '(age ' + this.age + ')'
})
}
}
var people = [];
people.push(new Person('Scott', 'German', 38));
people.push(new Person('Scott', 'Jones', 36));
people.push(new Person('Scott', 'Hanselman', 39));
people.push(new Person('Jessie', 'Liberty', 57));
people.push(new Person('John', 'Skeet', '38'));
function group(arr, prop)
{
var groupObj = {};
arr.forEach(function(person)
{
groupObj[person[prop]] ? (groupObj[person[prop]].push(person.toString())) : groupObj[person[prop]] = [person.toString()];
});
return groupObj;
}
//Log, as in assigment
console.log(group(people, 'firstName'));
console.log(group(people, 'lastName'));
console.log(group(people, 'age'));
//Human-readable table
console.table(group(people, 'firstName'));
console.table(group(people, 'lastName'));
console.table(group(people, 'age'));