JavaScript Tutorial in Hindi #19 | Advanced Array Methods & Techniques (2025)
✅ **1. .reduce()
– Reduce Array to a Single Value
Used to combine all items of an array into a single result (e.g., sum, product).
js
CopyEdit
let numbers = [10, 20, 30];
let total = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(total); // 60
✅ **2. .slice()
vs .splice()
– Know the Difference
MethodModifies Original?Purpose | ||
slice() | ❌ No | Extract a portion |
splice() | ✅ Yes | Add/Remove/Replace items |
🔹 slice(start, end)
– Non-destructive
js
CopyEdit
let arr = [1, 2, 3, 4];
console.log(arr.slice(1, 3)); // [2, 3]
🔹 splice(start, deleteCount, ...items)
– Destructive
js
CopyEdit
let colors = ["Red", "Green", "Blue"];
colors.splice(1, 1, "Yellow");
console.log(colors); // ["Red", "Yellow", "Blue"]
✅ 3. splice(start, deleteCount, ...items)
– Modify Original Array
- Start: index to start at
- DeleteCount: number of items to remove
- Items: new items to insert
js
CopyEdit
let fruits = ["Apple", "Banana", "Mango"];
fruits.splice(1, 0, "Orange"); // Insert at index 1
console.log(fruits); // ["Apple", "Orange", "Banana", "Mango"]
✅ 4. .concat()
& .flat()
🔹 concat()
– Combine arrays
js
CopyEdit
let a = [1, 2];
let b = [3, 4];
let c = a.concat(b);
console.log(c); // [1, 2, 3, 4]
🔹 flat()
– Flattens nested arrays (1 level by default)
js
CopyEdit
let nested = [1, [2, 3], [4, 5]];
console.log(nested.flat()); // [1, 2, 3, 4, 5]
✅ 5. Spread Operator ...
Expands array elements individually.
js
CopyEdit
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]
Also used in function calls:
js
CopyEdit
Math.max(...arr); // 3
✅ 6. Destructuring Arrays
Extract values from an array into variables easily.
js
CopyEdit
let [a, b, c] = [10, 20, 30];
console.log(a); // 10
console.log(c); // 30
You can also skip values:
js
CopyEdit
let [first, , third] = ["One", "Two", "Three"];
console.log(third); // "Three"