0

I have to call an api that returns an array of objects:

"supervisors": [
    {
        "jurisdiction": "u",
        "lastName": "Olson",
        "firstName": "Karson"
    },
    {
        "jurisdiction": "9",
        "lastName": "Heller",
        "firstName": "Robbie"
    },
    {
        "jurisdiction": "b",
        "lastName": "Cremin",
        "firstName": "Elijah"
    },
]

The supervisors must be sorted in alphabetical order, first by jurisdiction, then my last name, finally by first name. Then Numeric jurisdictions should be removed from the response.

I sorted alphabetically by:

supervisorsObj.sort((a, b) => {
      a.jurisdiction.toLowerCase().localeCompare(b.jurisdiction.toLowerCase());
    });

But how do I remove Numeric jurisdictions if they are all strings?

gog
  • 10,367
  • 2
  • 24
  • 38

2 Answers2

0

One option would be to use regular expressions, e.g

filtered = data.supervisors.filter(s => !/^\d+$/.test(s.jurisdiction))

will only remove jurisdictions that consists entirely of digits.

gog
  • 10,367
  • 2
  • 24
  • 38
0

The following snippet will first filter out all numeric .jurisdiction entries and will sort the remaining entries in a case-insensitive manner according to jurisdiction, lastName, firstName:

const supervisors= [
{
    "jurisdiction": "u",
    "lastName": "Olson",
    "firstName": "Karson"
},
{
    "jurisdiction": "9",
    "lastName": "Heller",
    "firstName": "Robbie"
},
{
    "jurisdiction": "b",
    "lastName": "Cremin",
    "firstName": "Elijah"
},
{
    "jurisdiction": "b",
    "lastName": "Cremmin",
    "firstName": "Elijah"
},
{
    "jurisdiction": "b",
    "lastName": "Cremin",
    "firstName": "Daniel"
},
{
    "jurisdiction": "b",
    "lastName": "Cremin",
    "firstName": "eddie"
}
];

const res=supervisors.filter(s=>isNaN(parseFloat(s.jurisdiction)))
  .sort((a,b)=>{
      let ab=0;
      ["jurisdiction","lastName","firstName"].some(p=>ab=a[p].toLowerCase().localeCompare(b[p].toLowerCase()));
      return ab;
});

console.log(res);

The actual comparisons take place in the inner .some() loop. The loop will stop processing as soon as it generates a result ab that is not equal to zero.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43