How to sort an array of objects based on the length of a nested array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects that contains nested array of objects like this −

const arr = [
   { name: "Cat1", elements : [
   { name: name, id: id } ]
},
{ name: "Cat2", elements : [
   { name: name, id: id },
   { name: name, id: id },
   { name: name, id: id } ]
},
{ name: "Cat3", elements : [
   { name: name, id: id },
   { name: name, id: id } ]
   }
];

We are required to write a JavaScript function that takes in one such array. The function should sort this array of objects.

The objects that contains more number of objects in the "elements" array property should rank higher.

Therefore, after sorting the array should look like this −

const output = [
   { name: "Cat2", elements : [
      { name: name, id: id },
      { name: name, id: id },
      { name: name, id: id } ]
   },
   { name: "Cat3", elements : [
      { name: name, id: id },
      { name: name, id: id } ]
   },
      { name: "Cat1", elements : [
      { name: name, id: id } ]
   }
];

Example

The code for this will be −

const arr = [
   { "name": "Cat1", elements : [
   { "name": "name", "id": "id" } ]
   },
   { "name": "Cat2", elements : [
   { "name": "name", "id": "id" },
   { "name": "name", "id": "id" },
   { "name": "name", "id": "id" } ]
   },
   { "name": "Cat3", elements : [
   { "name": "name", "id": "id" },
   { "name": "name", "id": "id" } ]
   }
];
const sorter = (a, b) => {
   if(a.elements.length > b.elements.length) {
      return −1;
   } else {
      return 1;
   }
}
arr.sort(sorter);
console.log(JSON.stringify(arr, undefined, 4));

Output

And the output in the console will be −

[
   {
      name": "Cat2",
      "elements": [
         {
            "name": "name",
            "id": "id"
         },
         {
            "name": "name",
            "id": "id"
         },
         {
            "name": "name",
            "id": "id"
         }
      ]
      },      
      {
         "name": "Cat3",
         "elements": [
      {
         "name": "name",
         "id": "id"
      },
      {
         "name": "name",
         "id": "id"
      }
      ]
   },
   {
      "name": "Cat1",
      "elements": [
         {
            "name": "name",
            "id": "id"
         }
      ]
   }
]
raja
Published on 23-Nov-2020 12:04:05
Advertisements