Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting JavaScript object by length of array properties.
Following is the code to sort JavaScript object by length of array properties −
Example
<!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 −

Advertisements