I'm trying to sort my array of objects in the following order:
- By ORDER First
- If a GROUP > 0 then matching group precedes over ORDER
Example:
var obj = [
{order:1, title:"Receipts", group:0},
{order:2, title:"Apples", group:1},
{order:7, title:"Costs", group:0},
{order:4, title:"Surplus", group:0},
{order:5, title:"Bananas", group:1},
{order:6, title:"Celery", group:2},
{order:8, title:"Documents", group:0},
{order:3, title:"Potatoes", group:2}
];
var newObj = obj.sort(function(a,b) {
return (a.order - b.order || b.group - a.group);
});
console.log(newObj);
//OUTPUT SHOULD LOOK LIKE THE FOLLOWING
/*
var newObj = [
{order:1, title:"Receipts", group:0},
{order:2, title:"Apples", group:1},
{order:5, title:"Bananas", group:1},
{order:3, title:"Potatoes", group:2}
{order:6, title:"Celery", group:2},
{order:4, title:"Surplus", group:0},
{order:7, title:"Costs", group:0},
{order:8, title:"Documents", group:0},
];
//ORDER OF LOGIC
1. Function sorts by order. Sees that the first entry has GROUP = 0, continues.
2. Function sees second entry has GROUP = 1. Function finds all objects with GROUP = 1
3. After all GROUP=1 objects have been found, function continues by ORDER (next ORDER:3 is at the bottom). Function sees GROUP = 2.
4. Function finds all objects with GROUP=2.
5. After all GROUP=2 objects have been found, function continues by ORDER. The remaining objects have GROUP=0 so no changes made.
*/
I tried to do it the easy way by using map... but I'm can't figure out how to do this. Should I just loop through the objects and when I find a record, pull it out and re-loop back through the array to find similar objects?