Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

Sort an array except one item using TypeScript

I have the following TypeScript code:

export const cgGroups = [
  {
    id: 2,
    name: 'North America & Caribbean'
  },
  {
    id: 3,
    name: 'Latin America'
  },
  {
    id: 6,
    name: 'Europe'
  },
  {
    id: 4,
    name: 'Asia Pacific'
  },
  {
    id: 1,
    name: 'Middle East & Africa'
  },
  {
    id: 7,
    name: 'International'
  }
];

I want to sort the above alphabetical except one object

{
   id: 7,
   name: 'International'
}

which I want to move it to the last of the sorted array.

I tried the below code to sort:

cgGroups = cgGroups.map(({id, name}) => ({id, name})).sort((a, b) => {
        if (a.name.toLowerCase() > b.name.toLowerCase()) {
          return 1;
        }
        if (a.name.toLowerCase() < b.name.toLowerCase()) {
          return -1;
        }
        return 0;
      });

Here is the expected output:

Asia Pacific, Europe, Latin America, Middle East & Africa, North America & Caribbean, and International

Can anyone guide me here to fix this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't work because you didn't encode the condition about the item with name: 'International' into the comparison function.

It could be like this:

cgGroups = cgGroups.map(({id, name}) => ({id, name})).sort((a, b) => {
    if (a.name.toLowerCase() == 'international') {
        return +1;      // "a" is the greatest element of the array
    } else if (b.name.toLowerCase() == 'international') {
        return -1;      // "a" stays before "b" because "b" is the last item
    } else if (a.name.toLowerCase() > b.name.toLowerCase()) {
        return 1;       // regular items, compare their names
    } else if (a.name.toLowerCase() < b.name.toLowerCase()) {
        return -1;
    }

    return 0;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...