-1

I am working on logframe and i want to sort my array in this order

  • Impact
  • Outcomes
  • Output
  • Activities

and i have array like this

{ id : 15 , parentId : 18 , type : OUTPUT , sequence : 1 },
{ id : 16 , parentId : 15 , type : OUTCOME , sequence : 1 },
{ id : 18 , parentId : null , type : IMPACT , sequence : 1 },
{ id : 14 , parentId : null , type : IMPACT , sequence : 2 },
{ id : 17 , parentId : 14, type : OUTCOME , sequence : 1 },

this was a raw data from database and order by via sequence

I wanted to sort it with all "IMPACT" type to be 1st on array and then so on ...

{ id : 18 , parentId : null , type : IMPACT , sequence : 1 },
{ id : 14 , parentId : null , type : IMPACT , sequence : 2 },
{ id : 16 , parentId : 15 , type : OUTCOME , sequence : 1 },
{ id : 17 , parentId : 14, type : OUTCOME , sequence : 2 },
{ id : 15 , parentId : 18 , type : OUTPUT , sequence : 1 },
Kevin Daniel
  • 51
  • 1
  • 1
  • 7
  • 1
    Duplicate covers the sorting array of objects by specific property part; if you need a “special order” within the values of that property, you can achieve that for example by specifying them in an array in the right order, and then check what index. – 04FS Feb 26 '19 at 15:50
  • i was really looking for special order but i dont know the right term on it. thanks for pointing it out :) really appreciate – Kevin Daniel Feb 26 '19 at 16:12

1 Answers1

0

Take a look at Array.sort, and pass your own custom comparison function to it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

For example, something like this should work:

arrayFromDatabase.sort(function(a, b) {
    if (a.type === IMPACT && b.type !== IMPACT) {
        return -1;
    } else if (a.type !== IMPACT && b.type === IMPACT) {
        return 1;
    } else {
        return a.sequence - b.sequence;
    }
});

Note that for brevity's sake, I left the other types you mentioned as an exercise for the reader.

Tyler Church
  • 649
  • 5
  • 8