How to group objects based on a value in JavaScript?



Following is the code to group objects based on a value in JavaScript −

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;    }    .result {       font-size: 18px;       font-weight: 500;       color: rebeccapurple;    } </style> </head> <body> <h1>Group objects based on a value in JavaScript</h1> <div class="result"> { name: 'Rohan', age: 18 }, { name: 'Mohan', age: 20 }, { name: 'Shawn', age: 18 }, { name: 'Michael', age: 18 }, { name: 'David', age: 20 } </div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to group the above object based on people's age</h3> <script>    let resEle = document.querySelector(".result");    let sampleEle = document.querySelector(".sample");    let BtnEle = document.querySelector(".Btn");    const people = [       { name: "Rohan", age: 18 },       { name: "Mohan", age: 20 },       { name: "Shawn", age: 18 },       { name: "Michael", age: 18 },       { name: "David", age: 20 },    ];    let groupBy = (array, key) => {       return array.reduce((result, obj) => {          (result[obj[key]] = result[obj[key]] || []).push(obj);          return result;       }, {});    };    let a = groupBy(people, "age");    BtnEle.addEventListener("click", () => {       console.log(a);    }); </script> </body> </html>

Output

The above code will produce the following output −

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

Updated on: 2020-07-21T07:00:19+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements