1

I have to sort JavaScript array with more than one filed combination and in that one field is combination of numbers & string.

My Code Snippet:

      emps = [
          {'first_name':'PQR','grade':'K'},
          {'first_name':'ABC','grade':'K'},
          {'first_name':'LMN','grade':'4'},
          {'first_name':'CDE','grade':'2'},
          {'first_name':'JKP','grade':'12'},
          {'first_name':'ASD','grade':'Others'}
      ];

I am able to sort above array using following code:

          emps.sort((a, b) => {
              
              if (a.grade === "K" || b.grade === "Other") {
                return -1;
              }
              if (a.grade === "Other" || b.grade === "K") {
                return 1;
              }
              return +a.grade - +b.grade;
          });

It's sorting gradewise accurately (K,1,2,3.....,12,Other) but I also want to sort it as per first_name with grade.

will you please suggest me the changes or script.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Hemant P
  • 129
  • 9
  • Do you want to sort by first_name first and then by grade? – domenikk Oct 12 '20 at 09:34
  • I think this one is more closely related: [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – emerson.marini Oct 12 '20 at 09:36

1 Answers1

2

You could sort with an object for the order and sort then by grade or first_name.

const emps = [{ first_name: 'PQR', grade: 'K' }, { first_name: 'ABC', grade: 'K' }, { first_name: 'LMN', grade: '4' }, { first_name: 'CDE', grade: '2' }, { first_name: 'JKP', grade: '12' }, { first_name: 'ASD', grade: 'Others' }],
      order = { K: -1, Others: 1, default: 0 };
      
emps.sort((a, b) =>
    (order[a.grade] || order.default) - (order[b.grade] || order.default) ||
    a.grade - b.grade ||
    a.first_name.localeCompare(b.first_name)
);

console.log(emps);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392