
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
Push Specific Elements to Last in 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.
So, 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} ];
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ { 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