Aggregation in JavaScript
Last Updated :
06 Dec, 2023
Aggregation is a fundamental concept in object-oriented programming that facilitates the creation of complex objects by combining simpler ones. It establishes a "has-a" relationship between objects, where one object contains references to other objects as its components. This relationship enhances code reusability and modularity in JavaScript applications.
Approach 1: Aggregation using Object Properties
- Create an object that contains properties representing the components you want to aggregate.
- These properties can be references to other objects, functions, or any data type.
- Establish an aggregation relationship by including one object within the other as a property.
- Allow one object to reference and use another, providing a way to model aggregation.
Example: In this example, we showcase aggregation in JavaScript with two book objects, book1
and book2
, aggregated within a library object, GFG
. The library object has methods to add books dynamically and display their information. A third book, book3
, is added to the library, and the display method is used to show details of all the books in the library.
JavaScript
const book1 = {
title: "The Great Gatsby",
author: "F.Scott Fitzgerald"
};
const book2 = {
title: "The GeeksforGeeks",
author: "Geek"
};
// Create an object representing a library that
// aggregates books
const GFG = {
name: "My Library",
books: [book1, book2],
addBook: function (book) {
this.books.push(book);
},
displayBooks: function () {
console.log(`Books in ${this.name}:`);
this.books.forEach((book, index) => {
console.log(
`${index + 1}. Title: ${book.title}, Author: ${book.author}`);
});
}
};
// Add more books
const book3 = {
title: "2023",
author: "George Orwell"
};
GFG.addBook(book3);
// Display the books
GFG.displayBooks();
OutputBooks in My Library:
1. Title: The Great Gatsby, Author: F.Scott Fitzgerald
2. Title: The GeeksforGeeks, Author: Geek
3. Title: 2023, Author: George Orwell
Approach 2 : Aggregation using Arrays
- Create an object that contains an array property to hold aggregated items.
- Perform operations like adding, removing, or manipulating items within the array.
- Aggregation starts with collecting data from various sources, such as user input, databases, or external files.
- Typically, store the collected data in an array data structure capable of holding multiple values of the same type.
- Arrays provide a way to represent a collection of related data items.
- Each item in the array is stored at a specific index, allows easy access and manipulation of individual elements.
- Arrays are often used to group and classify data, allowing effective organization, such as storing scores of students in a class.
Example: In this example, player objects are created using a constructor function, and a team object is formed to aggregate these players. The team object includes methods to add, remove, and display players. Additional players are added, the team is displayed, a player is removed, and the updated team is displayed.
JavaScript
function Players(name, age) {
this.name = name;
this.age = age;
}
// Create Player objects
const player1 = new Players("Kumar", 31);
const player2 = new Players("Bob", 29);
const team = {
name: "Red Team",
players: [player1, player2],
addPlayer: function (player) {
this.players.push(player);
},
removePlayer: function (playerName) {
const indexToRemove =
this.players.findIndex(player => player.name === playerName);
if (indexToRemove !== -1) {
this.players.splice(indexToRemove, 1);
}
},
displayTeam: function () {
console.log(`Team: ${this.name}`);
console.log("Players:");
this.players.forEach((player, index) => {
console.log(
`${index + 1}. Name: ${player.name}, Age: ${player.age}`);
});
}
};
// Add more players to the team
const player3 = new Players("Raj", 32);
team.addPlayer(player3);
// Display the team and its players
team.displayTeam();
team.removePlayer("Bob");
// Display the updated team
team.displayTeam();
OutputTeam: Red Team
Players:
1. Name: Kumar, Age: 31
2. Name: Bob, Age: 29
3. Name: Raj, Age: 32
Team: Red Team
Players:
1. Name: Kumar, Age: 31
2. Name: Raj, Age: 32
Similar Reads
JavaScript AggregateError object The JavaScript AggregateError object is used to reflect the overall error of many single errors. This can be used when multiple errors need to be represented in the form of a combined error, for example, it can be thrown by Promise.any() when all the promises passed to it are rejected. Construction:
2 min read
JavaScript Ellipsis JavaScript Ellipsis (also known as the spread/rest operator) is represented by three dots (...). It is used for various tasks, such as spreading elements of an array into individual values or collecting multiple values into an array or object. It simplifies data manipulation and function parameter h
3 min read
Grouping Nested Array in JavaScript Grouping nested arrays in JavaScript involves arranging arrays within arrays based on a common key or property. There are different approaches to group nested arrays in JavaScript which are as follows: Table of Content Using the reduce() methodUsing the forEach() method with an object as a mapUsing
3 min read
Sum of an Array in JavaScript There are multiple ways to calculate the sum of elements in an array in JavaScript. Here are some of the most common methods:1. Using for loop (Simple for all Array)A basic and straightforward way to sum the elements of an array is by using a for loop. This method iterates through each element in th
4 min read
JavaScript Grouping Operator The Grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. This operator can only contain expressions. The parameter li
2 min read
JavaScript Addition (+) Operator JavaScript addition (+) operator is one of the most fundamental and widely used arithmetic operators in JavaScript. It is used to perform arithmetic addition on numbers but also concatenate strings. Syntaxa + bWhere - a: The first value (number, string, or another data type).b: The second value (num
1 min read
How to Regroup JSON array in JavaScript Regrouping JSON arrays in JavaScript is crucial for organizing data efficiently, simplifying data management tasks, and ensuring better data integration across systems. Here, we will regroup JSON arrays in JavaScript in two methods to achieve this using the reduce method and an iterative approach. T
3 min read
JavaScript - Union of Arrays In JavaScript, finding the union of multiple arrays means combining their elements into a single array with only unique values. Here are several methods to compute the union of JavaScript ArraysUsing Spread Operator with Set - Most PopularWe can use the Set object along with the spread operator to f
3 min read
Must use JavaScript Array Functions â Part 3 Previous articles: Must use JavaScript Array Functions -Part 1 Must use JavaScript Array Functions -Part 2 In this article, we are going to discuss the following JavaScript array functions prototype.reduce()prototype.concat()prototype.sort()prototype.reverse() JavaScript Array.Prototype.reduce(): Ar
5 min read
How to Add the Numbers in a JavaScript Array? Adding the numbers in a JavaScript array is a common operation, particularly in tasks involving data aggregation or mathematical calculations. This process involves iterating through the array and summing its elements. JavaScript provides multiple methods to achieve this, ranging from traditional lo
2 min read