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