These arrays are useful for matrices, tables, grids, and structured datasets.
16. Arrays of Objects
In real-world applications, arrays frequently store multiple objects.
Example: Employee Records
let employees = [
{
name: "Rahul",
salary: 50000
},
{
name: "Priya",
salary: 60000
},
{
name: "Amit",
salary: 45000
}
];
console.log(employees[0].name);
console.log(employees[1].salary);
Output:
Rahul
60000
You can also filter employees based on salary:
let highSalary = employees.filter(
emp => emp.salary > 50000
);
console.log(highSalary);
This is commonly used when working with API responses and business applications.
17. Real-World Example: Shopping Cart
Let's build a simple shopping cart using JavaScript arrays.
let cart = [
{ name: "Laptop", price: 50000 },
{ name: "Mouse", price: 1000 },
{ name: "Keyboard", price: 2000 }
];
let total = cart.reduce((sum, item) => {
return sum + item.price;
}, 0);
console.log("Cart Items:", cart.length);
console.log("Total Amount:", total);
Output:
Cart Items: 3
Total Amount: 53000
This example combines arrays, objects, and the reduce() method.
18. Important Array Methods, Quick Revision
🔹 push() ➜ Adds an element at the end.
🔹 pop() ➜ Removes the last element.
🔹 shift() ➜ Removes the first element.
🔹 unshift() ➜ Adds an element at the beginning.
🔹 map() ➜ Transforms every element and returns a new array.
🔹 filter() ➜ Returns elements matching a condition.
🔹 reduce() ➜ Combines elements into a single result.
🔹 forEach() ➜ Executes a function for every element.
🔹 find() ➜ Returns the first matching element.
🔹 includes() ➜ Checks whether an element exists.
🔹 indexOf() ➜ Returns the first matching index.
🔹 slice() ➜ Extracts a portion without modifying the original array.
🔹 splice() ➜ Adds, removes, or replaces elements in the original array.
🔹 sort() ➜ Sorts array elements.
🔹 join() ➜ Converts array elements into a string.
Double Tap ❤️ For More26 11月, 06:34
