Sorting JavaScript object by length of array properties.


Following is the code to sort JavaScript object by length of array properties −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Sorting JavaScript object by length of array properties</h1>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to sort the objects inside arrObj based on Subject array length</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let arrObj = [
      { name: "Rohan", Subject: ["Maths", "Science", "EVS", "SST"] },
      { name: "Mohan", Subject: ["Maths", "Science", "SST"] },
      {
         name: "Shawn",
         Subject: ["Maths", "Physics", "Chemistry", "Biology", "German"],
      },
      {
         name: "Michael",
         Subject: ["Biology", "Hindi", "Sanskrit", "SST", "EVS", "Maths"],
      },
   ];
   BtnEle.addEventListener("click", () => {
      arrObj.sort((a, b) => (a.Subject.length > b.Subject.length ? 1 : -1));
      console.log(arrObj);
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button and inspecting output in console −

Updated on: 21-Jul-2020

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements