Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting JSON alphabetically by first letter

I have a JSON like this:

[
  {
    "id": 1,
    "slug": "abakan",
    "name": "Абакан"
  },
  {
    "id": 4,
    "slug": "almetevsk",
    "name": "Альметьевск"
  },
  {
    "id": 10,
    "slug": "astrahan",
    "name": "Астрахань"
  },
  {
    "id": 11,
    "slug": "barnaul",
    "name": "Барнаул"
  },
  ...
]

And getting this by this method:

public function getCities()
{
    $cities = City::mainCities()->get(['id', 'slug', 'name']);
    return response()->json($cities);
}

How can i sort this list alphabetically and with their letters. For example:

"A": [
  {
    "id": 1,
    "slug": "abakan",
    "name": "Абакан"
  },
  {
    "id": 4,
    "slug": "almetevsk",
    "name": "Альметьевск"
  }
],
"B": [
  {
    "id": 11,
    "slug": "barnaul",
    "name": "Барнаул"
  },
  ...
]

and so on...

I have Laravel on the backend and VueJS on front.

like image 362
pwnz22 Avatar asked Dec 01 '25 14:12

pwnz22


1 Answers

My solution:

var cities = [
  { id: 1, slug: "abakan", name: "Абакан" },
  { id: 4, slug: "almetevsk", name: "Альметьевск" },
  { id: 11, slug: "barnaul", name: "Барнаул" },
  { id: 10, slug: "astrahan", name: "Астрахань" }
];

cities.sort(function(a, b) {
  return a.slug[0].localeCompare(b.slug[0]);
});

var newCities = {};

for (var i = 0; i < cities.length; i++) {
  var c = cities[i].slug[0].toUpperCase();
  if (newCities[c] && newCities[c].length >= 0)
    newCities[c].push(cities[i]);
  else {
    newCities[c] = [];
    newCities[c].push(cities[i]);
  }
}

console.log(newCities);
like image 66
wannadream Avatar answered Dec 04 '25 06:12

wannadream



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!