skip to Main Content

i have the following array

"data": {
    "risks": [
      {
        "id": "22",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [],
        "num2": []
      },
      {
      "id": "55",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [],
        "num2": []
      },
      {
          "id": "33",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [1,2,3,4,5],
        "num2": [4,5,6,9]
      }
]}

is there a way to sort the array so the objects with empty num1 OR num2 to be last on the array ? i tried something like the following but it didnt work.

array.sort((x, y) => !!y.num1.length ==0- !!x.num1.length ==0|| !!y.num2.length ==0- !!x.num2.length ==0);

2

Answers


  1. You need to return an integer from the sort() method you implemented. Either 0 or > 0 or < 0 depending on the outcome of your comparison.

    One of the simplest ways to check that at least num1 or num2 in any of your objects contains an entity is to sum their lengths and compare, something like this:

    const obj = {data:{risks:[{id:"22",name:!0,surname:.5,age:.75,heigth:50,num1:[],num2:[]},{id:"55",name:!0,surname:.5,age:.75,heigth:50,num1:[],num2:[]},{id:"33",name:!0,surname:.5,age:.75,heigth:50,num1:[1,2,3,4,5],num2:[4,5,6,9]}]}};
    
    obj.data.risks = obj.data.risks.sort((a, b) => (b.num1.length + b.num2.length) - (a.num1.length + a.num2.length));
    console.log(obj.data.risks);

    Note that this approach is assuming that the arrays in the objects are always empty, never null.

    Login or Signup to reply.
  2. You could take the delta of the negated length for sorting empty arrays to bottom.

    const
        data = [{ id: "22", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [] }, { id: "55", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [1, 2, 3, 4, 5], num2: [4, 5, 6, 9] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [4, 5, 6, 9] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [4, 5, 6, 9] }];
        
    data.sort((a, b) =>
        !a.num1.length - !b.num1.length ||
        !a.num2.length - !b.num2.length
    );
        
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search