
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ]
- Related Questions & Answers
- Change string based on a condition - JavaScript
- Reorder an array in JavaScript
- Sorting Array based on another array JavaScript
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Find MongoDB records based on a condition?
- Modify an array based on another array JavaScript
- Appending a key value pair to an array of dictionary based on a condition in JavaScript?
- Converting decimal to binary or hex based on a condition in JavaScript
- Shuffling string based on an array in JavaScript
- SUM a column based on a condition in MySQL
- ORDER BY records in MySQL based on a condition
- Filter an object based on an array JavaScript
- Search and update array based on key JavaScript
- Shifting string letters based on an array in JavaScript
Advertisements