Useful Array Methods in Javascript - Part 1
1. forEach()
It used to iterate over an array and execute a function on each element.
Examples
const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
console.log(`Index: ${index}, Value: ${num}, Original array: ${arr}`);
});
// Output:
// Index: 0, Value: 1, Original array: 1, 2, 3, 4
// Index: 1, Value: 2, Original array: 1, 2, 3, 4
// Index: 2, Value: 3, Original array: 1, 2, 3, 4
// Index: 3, Value: 4, Original array: 1, 2, 3, 4
- It does not return a new array, unlike
map() - We can not chain it with other array methods
- Cannot use
breakorreturnto stop iteration. It throws "SyntaxError".
2. map()
This method creates a new array. Each element of the array is passed to a callback function, which transforms it and the result is collected into a new array.
Examples:
const numbers = [1, 2, 3, 4];
// Applying a function that doubles each number
const doubled = numbers.map(num => num * 2);
console.log(doubled);
// Output: [2, 4, 6, 8]
- Returns a new array but does not modify the original one.
- if callback does not return anything, the resulting array will be contain
undefined. - Returns a Shallow copy.
3. filter()
The filter() method creates a new array with elements that pass a test.
Examples:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
// Output: [2, 4]
- Returns a Shallow copy.
4. reduce()
The reduce() method reduces an array to a single value by applying a function repeatedly on each element.
Syntax:
array.reduce(callback(accumulator, currentValue, index, array), initialValue)
accumulator: Stores the accumulated result after each iteration.currentValue: The current array element.index: The index of the current element.array: The original array being processed.initialValue: The starting value of accumulator. If omitted, the first element of the array is used.
Examples:
1. Sum of numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);
// Output: 15
Explaination -
Loop Iteration 0 to 4 (total 5)
For 0th
- accumulator = 0
- currentValue = 1
- result => 0+1 = 1
For 1st
- accumulator = 1
- currentValue = 2
- result => 1+2 = 3
For 2nd
- accumulator = 3
- currentValue = 3
- result => 3+3 = 6
For 3rd
- accumulator = 6
- currentValue = 4
- result => 6+4 = 10
For 4th
- accumulator = 10
- currentValue = 5
- result => 10+5 = 15
2. Counting Occurrence of Elements (Word Frequency: Count how many times each word appears in an array)
const words = ["apple", "banana", "apple", "orange", "banana", "apple"];
const wordCount = words.reduce((accumulator,word)=>{
accumulator[word] = (accumulator[word] || 0) + 1;
return accumulator;
}, {}) // accumulator initialize with empty object
Explaination -
- We initialize
accumulatorwith empty object. - If the word exists in
accumulator, increase the count. - If not, initialize it with 0 and then add 1.
3. Flattening a Nested Array (Convert a multi-level array into a single array)
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattened = nestedArray.reduce((accumulator, array) => accumulator.concat(array), []);
Explaination -
- We initialize
accumulatorwith empty array. - Each inner array is concatenated into the
accumulator.
5. reduceRight()
The reduceRight() method is similar to reduce(), but it processes the array from right to left instead of left to right.
Syntax:
array.reduceRight(callback(accumulator, currentValue, index, array), initialValue)
Examples:
1. Reversing a String
const str = "hello";
const reversedStr = str.split("").reduceRight((acc, char) => acc + char, "");
console.log(reversedStr);
// Output: "olleh"
6. concat()
The concat() method in JavaScript is used to merge two or more arrays into a new array. It does not modify the original arrays but instead returns a new array.
Syntax:
const newArray = array1.concat(array2, array3, ...);
Examples:
-
Merging Multiple Arrays
const arr1 = [1, 2]; const arr2 = [3, 4]; const arr3 = [5, 6]; const mergedArray = arr1.concat(arr2, arr3); console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6] -
Intersting Issue While Concatenating Nested Arrays
const arr1 = [[1, 2]]; const arr2 = [[3, 4]]; const merged = arr1.concat(arr2); console.log(merged); // Output: [[1, 2], [3, 4]] merged[0][0] = 99; console.log(arr1); // Output: [[99, 2]] (Unexpected mutation)Why did
arr1change?- concat() creates a new array, but it does not deep copy nested arrays.
- It copies object references, meaning modifying
merged[0]also modifiesarr1.