Array is most important part of Javascript.They store list of data like numbers, name, products etc so let's look at some methods to manipulate array
1. push() and pop()
They work at the end of the array
- push() : adds at the end
Before:
let fruits =["apple","banana"]
fruits.push("orange")
After:
["apple","banana","orange"]
Push adds item in the array and changes the array
- pop(): removes from the end
Before:
let fruits = ["apple","banana","orange"]
fruits.pop()
After:
["apple","banana"]
Pop removes last item from the array and changes the array
2. shift() and unshift()
These work at beginning of array
- unshift() : add the beginning of array
Before:
let numbers = [2,3,4]
numbers.unshift(1)
After:
[1,2,3,4]
- shift() : remove from the beginning of array
Before:
let numbers =[1,2,3,4]
numbers.shift()
after:
numbers.shift()
3.map()
creates a new array by transforming each item
for example if we want double the number in array
let numbers=[1,2,3]
let doubled = numbers.map(e=>e*2)
console.log(doubled)
[1,2,6]
console.log(numbers)
[1,2,3]
How map works:
[1, 2, 3]
↓
×2 ×2 ×2
↓
[2, 4, 6]
`
4.filter()
Creates a new array with only matching items
let numbers = [1,2,3,4]
let filtered = numbers.filter(e=>e>2)
console.log(filtered)
[3,4]
console.log(numbers)
[1,2,3,4]
How Filter works
[1,2,3,4]
❌ ❌ ✅ ✅
[3,4]
5. reduce()
Reduce combines all values into single value
example: Find total Sum
let array= [1,2,3,4]
let value = array.reduce((acc,currentvalue)=>return acc + currentvalue,0)
console.log(value)
10
Simple explanation
acc : stores the running total
currentvalue :current number
0:starting value
How reduce works:
start: 0
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
6. foreach
Used to loop through array
let numbers = [1,2,3]
numbers.foreach(function(num)=> console.log(num))
`
output:
1
2
3
`
Mutating Methods (Change Original Array)
- push() → Add to end
- pop() → Remove from end
- shift() → Remove from start
- unshift() → Add to start All of these: ❌ Do NOT return new array ✅ Modify the original array
Non-Mutating Methods (Do NOT Change Original)
- map() → Transform data → ✅ Returns new array
- filter() → Select data → ✅ Returns new array
- forEach() → Loop only → ❌ Returns nothing
- reduce() → Combine values → ❌ Returns single value
Top comments (0)