I have the following code( function named group) which groups people objects from persons array into arrays by a certain property(belonging to person object) inside an associative array. So groups(arrays) of people are placed into the resulting associative array by a key that is the property value. For example we have an array that is created and stored into the final array by lastname='Bunny': all the four people from persons with last name Bunny. The problem is that when I do a for in loop trying to display the objects I have at the end of every group an undefined object. This does not happen if I go through the array/object with a for loop. But I can not do it with the associative array since it does not have indexes. I wanted to know why does console.log display an undefined value, can it do something with the prototype? Thanks.
persons=[
{ firstname: 'Funny', lastname: 'Bunny', age: 32 },
{ firstname: 'Little', lastname: 'Bunny', age: 12 },
{ firstname: 'Buggs', lastname: 'Bunny', age: 42 },
{ firstname: 'Ivan', lastname: 'Petrov', age: 52 },
{ firstname: 'Honey', lastname: 'Bunny', age: 22 },
{ firstname: 'John', lastname: 'Doe', age: 32 },
{ firstname: 'Mike', lastname: 'Doe', age: 22 }
];
function group(personsArray, groupType) {
var associativeArray = {};
for (var i in personsArray) {
if (!associativeArray[personsArray[i][groupType]]) {
associativeArray[personsArray[i][groupType]] = [];
}
associativeArray[personsArray[i][groupType]].push(personsArray[i]);
}
return associativeArray;
}
var res = group(persons, 'lastname');
for (var item in res) {
console.log('GROUP: ' + item);
for (var i = 0; i < res[item].length; i++) {
console.log((res[item])[i].firstname);
}
}
Output:
GROUP: Bunny
Funny
Little
Buggs
Honey
GROUP: Petrov
Ivan
GROUP: Doe
John
Mike
GROUP: undefined
undefined