Answer the question
In order to leave comments, you need to log in
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}
];
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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question