javascript – How to insert a specific element of an array into the first place?

Question:

There is a lexicographically sorted array of objects obtained from the api, where there is one of the properties – the name of the city (Name). I need to sort so that the city I need goes first, and all the rest are alphabetical.

const result = response.data
          result.sort( (a, b) => {
            return a.Name.localeCompare(b.Name)
          });

Is it possible to somehow set such a sorting order so that at first a certain city would be in the first place, say "Moscow", and then all other elements would be sorted lexicographically? I tried to do something like this:

if(a.Name === 'Москва') {
return 1;
}
if (a.Name < b.Name) {
  return -1;
  }
return 0;

But this is not at all the same …

Answer:

You can do this

const arr = [
  {Name: 'НеМосква1'},
  {Name: 'НеМосква2'},
  {Name: 'Москва'},
  {Name: 'НеМосква3'}
];

var result = arr.sort( (a, b) => {
        if(a.name == "Москва") return -1;
        if(b.name == "Москва") return 1;
        return a.Name.localeCompare(b.Name)
    })

console.log(result);
Scroll to Top