I have some data formatted like this:
var data = [
{ id: 1, name: "Netherlands", population: 17},
{ id: 1.1, name: "Rotterdam", population: 4},
{ id: 1.2, name: "Amsterdam", population: 2},
{ id: 2, name: "USA", population: 350},
{ id: 3, name: "Germany", population: 55},
{ id: 3.1, name: "Berlin", population: 4},
{ id: 3.2, name: "Stuttgard", population: 3},
{ id: 3.3, name: "Cologne", population: 3},
{ id: 4, name: "UK", population: 60},
{ id: 5, name: "Canada", population: 30},
{ id: 5.1, name: "Ottawa", population: 2},
];
Basically, the name can be either a city or a country. Countries are designated as integers, and their cities as .1. Each country can have 0-3 cities.
Is it possible to write a comparator function for Array.prototype.sort, where it sorts, for example, countries in alphabetical order, and then by their cities, but preserves the integrity of the country / city group and does not mutate the data array in advance? Is it possible? If not, why? If this is not possible, it would still be interesting for me to know how to do this, sorting through the array first, although for this I would need a lot more bounce, and this is not ideal.
, :
var data = [
{ id: 5, name: "Canada", population: 30},
{ id: 5.1, name: "Ottawa", population: 2},
{ id: 3, name: "Germany", population: 55},
{ id: 3.1, name: "Berlin", population: 4},
{ id: 3.3, name: "Cologne", population: 3},
{ id: 3.2, name: "Stuttgard", population: 3},
{ id: 1, name: "Netherlands", population: 17},
{ id: 1.2, name: "Amsterdam", population: 2},
{ id: 1.1, name: "Rotterdam", population: 4},
{ id: 4, name: "UK", population: 60},
{ id: 2, name: "USA", population: 350},
];
, :
http://plnkr.co/edit/vPTaoh
, / array.prototype.sort , , , . .