Advertisement
aslv

Group People

Jul 23rd, 2014
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Person(firstName, lastName, age) {
  2.     this.firstName = firstName;
  3.     this.lastName = lastName;
  4.     this.age = age;
  5. }
  6.  
  7. var people = [];
  8. people.push(new Person("Scott", "Guthrie", 38));
  9. people.push(new Person("Scott", "Johns", 36));
  10. people.push(new Person("Scott", "Hanselman", 39));
  11. people.push(new Person("Jesse", "Johns", 57));
  12. people.push(new Person("Jon", "Skeet", 38));
  13.  
  14. function group(array, property) {
  15.     var result = {};
  16.     var person;
  17.     for (i in array) {
  18.         person = array[i];
  19.         if (!(property in person)) {
  20.             continue;
  21.         }
  22.         if (person[property] in result) {
  23.             result[person[property]].push(person);
  24.         }
  25.         else {
  26.             result[person[property]] = [person];
  27.         }
  28.     }
  29.     console.log(result);
  30.     console.log();
  31. }
  32.  
  33. group(people, 'firstName');
  34. group(people, 'age');
  35. group(people, 'lastName');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement