Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sort an array to have specific items first in the array - JavaScript
Suppose, we have an array of objects like this −
const arr = [
{flag: true, other: 1},
{flag: true, other: 2},
{flag: false, other: 3},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6},
{flag: false, other: 7}
];
We are required to write a JavaScript function that takes in one such array and sorts it based on the following conditions −
- If arr.flag === false, the matching element gets placed first in the array, but only after the previous matching elements.
- The elements that do not match, remain in the same order they were in originally.
- Order of appearance is important.
Therefore, for the above array, the output should be −
const output = [
{flag: false, other: 3},
{flag: false, other: 7},
{flag: true, other: 1},
{flag: true, other: 2},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6}
];
Example
Following is the code −
const arr = [
{flag: true, other: 1},
{flag: true, other: 2},
{flag: false, other: 3},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6},
{flag: false, other: 7}
];
const sortByFlag = arr => {
const sorter = (a, b) => {
if(!a['flag'] && b['flag']){
return -1;
};
if(a['flag'] && !b['flag']){
return 1;
}
return a['other'] - b['other'];
}
arr.sort(sorter);
};
sortByFlag(arr);
console.log(arr);
Output
This will produce the following output on console −
[
{ flag: false, other: 3 },
{ flag: false, other: 7 },
{ flag: true, other: 1 },
{ flag: true, other: 2 },
{ flag: true, other: 4 },
{ flag: true, other: 5 },
{ flag: true, other: 6 }
]Advertisements