let numbers = [10, 20, 30, 40, 50];
let result = numbers.slice(1, 4);
console.log(result);
Output: [20, 30, 40]
D. splice()
Adds, removes, or replaces elements in the original array.
fruits.splice(1, 1, "Orange");
console.log(fruits);
Output: ["Apple", "Orange", "Banana"]
Here:
• 1 ➜ Starting index.
• 1 ➜ Number of elements to remove.
• "Orange" ➜ New element to insert.
8. Iterating Through Arrays
You can use loops to access every element in an array.
A. Using for Loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
B. Using for...of
for (let fruit of fruits) {
console.log(fruit);
}
C. Using forEach()
Executes a callback function for each array element.
let numbers = [10, 20, 30];
numbers.forEach(function(num) {
console.log(num);
});
9. map() Method
The map() method creates a new array by transforming every element of the original array.
Example: Multiply Every Number by 2
let numbers = [1, 2, 3, 4, 5];
let result = numbers.map(num => num * 2);
console.log(result);
Output:
[2, 4, 6, 8, 10]
Use case: Transforming data, formatting values, and preparing information for display.
10. filter() Method
The filter() method creates a new array containing elements that satisfy a given condition.
Example: Find Even Numbers
let numbers = [1, 2, 3, 4, 5, 6];
let result = numbers.filter(num => num % 2 === 0);
console.log(result);
Output:
[2, 4, 6]
Use case: Filtering products, employees, customers, and records based on conditions.
11. reduce() Method
The reduce() method processes array elements and combines them into a single accumulated result.
Example: Calculate Total
let numbers = [10, 20, 30, 40];
let total = numbers.reduce((sum, num) => {
return sum + num;
}, 0);
console.log(total);
Output: 100
Use case: Calculating totals, sums, averages, and aggregations.
12. find() Method
Returns the first element that satisfies a specified condition.
let numbers = [10, 20, 30, 40];
let result = numbers.find(num => num > 20);
console.log(result);
Output: 30
Unlike filter(), find() returns only the first matching element.
13. sort() Method
Used to sort array elements.
let numbers = [40, 10, 30, 20];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output: [10, 20, 30, 40]
For descending order:
numbers.sort((a, b) => b - a);
console.log(numbers);
Important: Calling sort() directly without a comparator sorts elements as strings by default.
14. Joining Array Elements
The join() method combines array elements into a single string.
let result = fruits.join(", ");
console.log(result);
Output:
Apple, Mango, Banana
15. Multidimensional Arrays
A multidimensional array contains other arrays as elements.
let numbers = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(numbers[0][1]);
console.log(numbers[2][2]);
Output:
2
9