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 } ]
Advertisements