Reorder array based on condition in JavaScript?



Let’s say we have an array of object that contains the scores of some players in a card game βˆ’

const scorecard = [{
   name: "Zahir",
   score: 23
}, {
      name: "Kabir",
      score: 13
}, {
      name: "Kunal",
      score: 29
}, {
      name: "Arnav",
      score: 42
}, {
      name: "Harman",
      score: 19
}, {
      name: "Rohit",
      score: 41
}, {
      name: "Rajan",
      score: 34
}];

We also have a variable by the name of selfName that contains the name of a particular player βˆ’

const selfName = 'Arnav';

We are required to write a function that sorts the scorecard array in alphabetical order and makes sure the object with name same as selfName appears at top (at index 0).

Therefore, let’s write the code for this problem βˆ’

Example

const scorecard = [{
   name: "Zahir",
   score: 23
}, {
      name: "Kabir",
      score: 13
}, {
      name: "Kunal",
      score: 29
}, {
      name: "Arnav",
      score: 42
}, {
      name: "Harman",
      score: 19
}, {
      name: "Rohit",
      score: 41
}, {
      name: "Rajan",
      score: 34
}];
const selfName = 'Arnav';
const sorter = (a, b) => {
   if(a.name === selfName){
      return -1;
   };
   if(b.name === selfName){
      return 1;
   };
   return a.name < b.name ? -1 : 1;
};
scorecard.sort(sorter);
console.log(scorecard);

Output

The output in the console will be βˆ’

[
   { name: 'Arnav', score: 42 },
   { name: 'Harman', score: 19 },
   { name: 'Kabir', score: 13 },
   { name: 'Kunal', score: 29 },
   { name: 'Rajan', score: 34 },
   { name: 'Rohit', score: 41 },
   { name: 'Zahir', score: 23 }
]
Updated on: 2020-08-26T11:35:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements