F
F
FrontDev922021-06-24 08:25:31
JavaScript
FrontDev92, 2021-06-24 08:25:31

How to properly sort an array of objects?

There is an array:

cities = [
    {city: "Артёмовск", population: 1688},
    {city: "Ачинск", population: 105259},
    {city: "Боготол", population: 19819},
    {city: "Бородино", population: 16061},
    {city: "Дивногорск", population: 29195},
    {city: "Дудинка", population: 21015},
    {city: "Енисейск", population: 17805},
    {city: "Железногорск", population: 83857},
    {city: "Заозёрный", population: 10286},
    {city: "Красноярск", population: 1095286}
    ];

You need to sort it alphabetically, but put the city with the highest population value in the first place.

I try like this:

function sortData(arr) {
        const max = arr.reduce((prev,cur) => +cur.population > +prev.population ? cur: prev);  //нахожу город с максимальным населением
        const maxIndex = arr.findIndex(item => item.city === max.city); //нахожу индекс этого объекта в массиве
        arr.splice(maxIndex, 1);  // вырезаю его
        arr = arr.sort((a, b) => a.city.toLowerCase() - b.city.toLowerCase());  // провожу сортировку по алфавиту
        arr.unshift(max);  // вставляю в начало город с максимальным населением
        return arr;
    }

The function works, but it seems to me that I'm missing something...
Is it possible to raise the city with the maximum population somehow simpler (perhaps at the sorting stage) and bypass finding the maximum element, cutting and pasting it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-24
@FrontDev92

function sort([...arr]) {
  const max = arr.reduce((max, n) => max?.population > n.population ? max : n, null);
  return arr.sort((a, b) => a === max ? -1 : b === max ? 1 : a.city.localeCompare(b.city));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question