DEV Community

Hiral
Hiral

Posted on

Array Methods You Must Know

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")
Enter fullscreen mode Exit fullscreen mode

After:

["apple","banana","orange"]
Enter fullscreen mode Exit fullscreen mode

Push adds item in the array and changes the array

- pop(): removes from the end

Before:

let fruits = ["apple","banana","orange"]
fruits.pop()
Enter fullscreen mode Exit fullscreen mode

After:

["apple","banana"]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

After:

[1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

- shift() : remove from the beginning of array

Before:

let numbers =[1,2,3,4]
numbers.shift()
Enter fullscreen mode Exit fullscreen mode

after:

numbers.shift()
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

How map works:

[1, 2, 3]
   ↓
×2  ×2  ×2
   ↓
[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

`
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)