Search code examples
javascriptservicenow

I need help to reorder array.object considering a specific element


I have this array.object and I need to reorder it so that if it has an empty displayOrder it will be last considering the type.

[
  {
    "displayOrder": "",
    "type": "moment",
  },
  {
    "displayOrder": "2",
    "type": "moment",
  },
  {
    "displayOrder": "4",
    "type": "moment",
  },
  {
    "displayOrder": "1",
    "type": "presentation",
  }
]

//Reorder to this:

[

  {
    "displayOrder": "2",
    "type": "moment",
  },
  {
    "displayOrder": "4",
    "type": "moment",
  },
  {
    "displayOrder": "",
    "type": "moment",
  },
  {
    "displayOrder": "1",
    "type": "presentation",
  }
]

What could I do to achieve this?


Solution

  • To obtain what you need, you can simply specifying a function and pass it to the Array.prototype.sort() method. I've tried something along this line, but you can adapt it according to your needs.

    let array = [
        {
            "displayOrder": "",
            "type": "moment",
        },
        {
            "displayOrder": "2",
            "type": "moment",
        },
        {
            "displayOrder": "4",
            "type": "moment",
        },
        {
            "displayOrder": "1",
            "type": "presentation",
        }
    ];
    
    array.sort((a, b) => {
        if (a.type === b.type) {
            if (b.displayOrder === '') return -1;
            if (a.displayOrder === '') return 1;
            return Number(a.displayOrder) > Number(b.displayOrder) ? 1 : -1;
        }
        if (a.type !== b.type) return (a.type < b.type) ? -1 : 1;
        return (a.displayOrder < b.displayOrder) ? -1 : (a.displayOrder > b.displayOrder) ? 0 : 1;
    });
    
    console.log(array);