screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Group Array of Objects</title> </head> <body> <h3>Javascript Group Array of Objects by Key</h3> <p>Click the button to show grouped data</p> <button onclick="groupData()">Group Data</button> <div id="result"></div> <script> const data = [ { id: 1, name: 'Apple', category: 'fruit' }, { id: 2, name: 'Tomato', category: 'vegetable' }, { id: 3, name: 'Doll', category: 'Toy' }, { id: 4, name: 'Banana', category: 'fruit' }, { id: 5, name: 'Carrot', category: 'vegetable' }, { id: 6, name: 'Teddy Bear', category: 'Toy' }, { id: 7, name: 'Orange', category: 'fruit' }, { id: 8, name: 'Broccoli', category: 'vegetable' }, { id: 9, name: 'Action Figure', category: 'Toy' }, // Add more items as needed ]; function groupData() { const groupedData = data.reduce((result, item) => { (result[item.category] = result[item.category] || []).push(item); return result; }, {}); // Display the grouped data on the webpage const resultDiv = document.getElementById('result'); resultDiv.innerHTML = '<h2>Grouped Data:</h2>'; for (const category in groupedData) { resultDiv.innerHTML += `<p>${category}: ${JSON.stringify(groupedData[category])}</p>`; } } </script> </body> </html>