Top JavaScript Array Methods with Examples
Illustration of JavaScript array methods like map, filter, push, pop with example code
Are you looking to master JavaScript array methods with practical examples? Whether you're a beginner or brushing up on your skills, this guide covers the most-used JavaScript array functions that will boost your coding efficiency.
1. push()
– Add Element to the End
let fruits = ['apple', 'banana'];
fruits.push('orange');
// ['apple', 'banana', 'orange']
2. pop()
– Remove Last Element
fruits.pop();
// ['apple', 'banana']
3. unshift()
– Add Element to the Beginning
fruits.unshift('mango');
// ['mango', 'apple', 'banana']
4. shift()
– Remove First Element
fruits.shift();
// ['apple', 'banana']
5. map()
– Transform Array Items
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
// [2, 4, 6]
6. filter()
– Filter Items Based on Condition
let even = numbers.filter(num => num % 2 === 0);
// [2]
7. reduce()
– Sum or Combine Array Values
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
// 6
8. find()
– Find First Matching Element
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
let user = users.find(u => u.id === 2);
// { id: 2, name: 'Bob' }
9. some()
– Check If Any Item Matches Condition
let hasEven = numbers.some(n => n % 2 === 0);
// true
10. every()
– Check If All Items Match Condition
let allEven = numbers.every(n => n % 2 === 0);
// false
11. forEach()
– Loop Through Each Item
numbers.forEach(n => console.log(n));
12. includes()
– Check If Value Exists
let items = ['pen', 'pencil', 'eraser'];
console.log(items.includes('pen'));
// true
13. indexOf()
– Get Position of Item
console.log(items.indexOf('pencil'));
// 1
14. slice()
– Extract Portion of an Array
let part = numbers.slice(1, 3);
// [2, 3]
15. splice()
– Add or Remove Elements
items.splice(1, 1, 'marker');
// ['pen', 'marker', 'eraser']
Bonus: Chain Array Methods
let result = [1, 2, 3, 4, 5]
.filter(n => n % 2 !== 0)
.map(n => n * 10);
// [10, 30, 50]
Understanding these JavaScript array methods is crucial for writing clean and efficient code. Practice these examples to boost your skills and confidence in handling arrays in real-world projects.