如何在 JavaScript 中按 Id 對物件陣列進行分組?
以下是按 Id 在 JavaScript 中對物件陣列進行分組的程式碼 −
示例
<!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 the array of objects by Id 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 sort the above object based on peoples 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>輸出
上述程式碼將產生以下輸出 −

點選“單擊此處”按鈕並檢查控制檯中的輸出 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP