- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 } ]
- Related Articles
- Sort an integer array, keeping first in place in JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- Sort an array according to another array in JavaScript
- How to sort array by first item in subarray - JavaScript?
- Using merge sort to recursive sort an array JavaScript
- Find the least duplicate items in an array JavaScript
- Odd even sort in an array - JavaScript
- JavaScript Bubble sort for objects in an array
- Sort by index of an array in JavaScript
- Completely removing duplicate items from an array in JavaScript
- How to sort an array of integers correctly in JavaScript?
- How to sort an array in JavaScript?Explain with example?
- How to find specific words in an array with JavaScript?
- Finding the first redundant element in an array - JavaScript
- Constructing an array of addition/subtractions relative to first array element in JavaScript

Advertisements