Advertisement
dimipan80

Group Persons

Nov 19th, 2014
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function group(persons) that groups an array of persons by age, first or last name.
  2.  Create a Person constructor to add every person in the person array. The group(persons) function must return
  3.  an associative array, with keys – the groups (age, firstName and lastName) and values – arrays with persons
  4.  in this group. Print on the console every entry of the returned associative array. */
  5.  
  6. "use strict";
  7.  
  8. function Person(firstName, lastName, age) {
  9.     return {
  10.         "firstName": firstName,
  11.         "lastName": lastName,
  12.         "age": age,
  13.         "toString": function () {
  14.             return this.firstName + ' ' + this.lastName + '(age ' + this.age + ')';
  15.         }
  16.     };
  17. }
  18.  
  19. function group(persons) {
  20.     var keyGroup = arguments[1];
  21.     if (!keyGroup) return persons;
  22.  
  23.     var groupObj = {};
  24.     for (var i = 0; i < persons.length; i += 1) {
  25.         var person = persons[i];
  26.         var groupName = 'Group ';
  27.         switch (keyGroup) {
  28.             case 'firstName':
  29.                 groupName = groupName.concat(person.firstName);
  30.                 break;
  31.             case 'lastName':
  32.                 groupName = groupName.concat(person.lastName);
  33.                 break;
  34.             case 'age':
  35.                 groupName = groupName.concat(person.age);
  36.                 break;
  37.         }
  38.  
  39.         if (!(groupName in groupObj)) {
  40.             groupObj[groupName] = [];
  41.         }
  42.  
  43.         groupObj[groupName].push(person.toString());
  44.     }
  45.  
  46.     return groupObj;
  47. }
  48.  
  49.  
  50. var people = [];
  51. people.push(new Person("Scott", "Guthrie", 38));
  52. people.push(new Person("Scott", "Johns", 36));
  53. people.push(new Person("Scott", "Hanselman", 39));
  54. people.push(new Person("Jesse", "Liberty", 57));
  55. people.push(new Person("Jon", "Skeet", 38));
  56.  
  57. console.log(group(people, 'firstName'));
  58. console.log(group(people, 'age'));
  59. console.log(group(people, 'lastName'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement