Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function group(persons) that groups an array of persons by age, first or last name.
- Create a Person constructor to add every person in the person array. The group(persons) function must return
- an associative array, with keys – the groups (age, firstName and lastName) and values – arrays with persons
- in this group. Print on the console every entry of the returned associative array. */
- "use strict";
- function Person(firstName, lastName, age) {
- return {
- "firstName": firstName,
- "lastName": lastName,
- "age": age,
- "toString": function () {
- return this.firstName + ' ' + this.lastName + '(age ' + this.age + ')';
- }
- };
- }
- function group(persons) {
- var keyGroup = arguments[1];
- if (!keyGroup) return persons;
- var groupObj = {};
- for (var i = 0; i < persons.length; i += 1) {
- var person = persons[i];
- var groupName = 'Group ';
- switch (keyGroup) {
- case 'firstName':
- groupName = groupName.concat(person.firstName);
- break;
- case 'lastName':
- groupName = groupName.concat(person.lastName);
- break;
- case 'age':
- groupName = groupName.concat(person.age);
- break;
- }
- if (!(groupName in groupObj)) {
- groupObj[groupName] = [];
- }
- groupObj[groupName].push(person.toString());
- }
- return groupObj;
- }
- var people = [];
- people.push(new Person("Scott", "Guthrie", 38));
- people.push(new Person("Scott", "Johns", 36));
- people.push(new Person("Scott", "Hanselman", 39));
- people.push(new Person("Jesse", "Liberty", 57));
- people.push(new Person("Jon", "Skeet", 38));
- console.log(group(people, 'firstName'));
- console.log(group(people, 'age'));
- console.log(group(people, 'lastName'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement