Imagine you have a collection of objects with various attributes like this:
var entities = [
{ name: 'Seymour Skinner', role: 'Principal' },
{ name: 'Kwik-E-Mart', lat: 23, long: 100 },
{ name: 'Sideshow Bob', role: 'Comic Foil' },
{ name: 'Flaming Tyre Yard', lat: 12, long: 88 },
{ name: 'Joe Quimby', role: 'Mayor' }
];
If you wish to group them into separate lists as shown below:
locations = [
{ name: 'Kwik-E-Mart', lat: 23, long: 100 },
{ name: 'Flaming Tyre Yard', lat: 12, long: 88 }
];
characters = [
{ name: 'Seymour Skinner', role: 'Principal' },
{ name: 'Sideshow Bob', role: 'Comic Foil' },
{ name: 'Joe Quimby', role: 'Mayor' }
];
You can achieve this using the built-in Array.filter
method as demonstrated in the code snippet below:
var locations = entities.filter(function(entity) {
if (entity.role !== undefined) {
// it is a character since locations do not have roles
return true;
} else {
return false;
}
});
var characters = entities.filter(function(entity) {
if (entity.lat !== undefined && entity.long !== undefined) {
// it is a location since characters do not have coordinates
return true;
} else {
return false;
}
});