Mastering JavaScript Array Methods
JavaScript provides powerful array methods that make working with data easier and more efficient. Whether you’re a beginner or an experienced developer, understanding these methods can help you write clean and more readable code.
Let’s explore some commonly used JavaScript array methods with practical examples.
- push() & pop():
push()
: Adds elements to the end of an array.pop()
: Removes the last element from an array.
let numbers = [1, 2, 3];
// Add 4 to the end
numbers.push(4); // [1, 2, 3, 4]
// Remove the last element
numbers.pop(); // [1, 2, 3]
2. unshift() & shift():
unshift()
: Adds elements at the start.shift()
: Removes the first element.
let peoples = ["sandeep", "manoj"];
// Add "harry" to the beginning
peoples.unshift("harry"); // ["harry", "sandeep", "manoj"]
// Remove the first element
peoples.shift(); // ["sandeep", "manoj"]
3. Map():
Creates a new array by applying a function to each element.
let numbers = [1, 2, 3];
let updatedNumbers= numbers.map(num => num + num);
console.log(updatedNumbers); // [2, 4, 6]
4. filter():
Creates a new array with elements that pass a condition.
let ages = [18, 25, 15, 30];
let eligibleVotersAges = ages.filter(age => age >= 18);
console.log(eligibleVotersAges); // [18, 25, 30]
5. reduce():
Used for sum, average, multiplication, and more.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
6. find():
Returns the first element that matches a condition.
let users = [
{ name: "Sandeep", age: 25 },
{ name: "Harry", age: 26 }
];
let user = users.find(user => user.age > 25);
console.log(user); // { name: "Harry", age: 26 }
7. some() & every():
a. some()
: Returns true if at least one element matches.
b. every()
: Returns true if all elements match.
let scores = [85, 90, 78];
let hasHighScore = scores.some(score => score > 90);
console.log(hasHighScore); // false
let allPassed = scores.every(score => score >= 50);
console.log(allPassed); // true
8. includes():
checks if an array contains an element.
let animal = ["dog", "lion", "tiger"];
console.log(colors.includes("dog")); // true
console.log(colors.includes("elephant")); // false
9. sort():
Sorts alphabetically by default. For numbers, provide a compare function.
let numbers = [4, 2, 9, 1];
// Incorrect: sorts as strings
console.log(numbers.sort()); // [1, 2, 4, 9]
// Correct: Sort numerically
console.log(numbers.sort((a, b) => a - b)); // [1, 2, 4, 9]
10. splice() & slice():
splice(start, count)
: removes/updates elements.slice(start, end)
: extracts part of an array (without modifying).
let months = ["Jan", "Feb", "Mar", "Apr"];
// Remove 1 item at index 1
months.splice(1, 1);
console.log(months); // ["Jan", "Mar", "Apr"]
// Extract ["Feb", "Mar"]
let newMonths = ["Jan", "Feb", "Mar", "Apr"].slice(1, 3);
console.log(newMonths); // ["Feb", "Mar"]
11. flat():
The flat()
method flattens nested arrays into a single array.
let arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]
12. join():
Joins array elements into a string with a specified separator.
let words = ["Sandeep", "is", "awesome"];
console.log(words.join(" ")); // "Sandeep is awesome"
console.log(words.join("-")); // "Sandeep-is-awesome"
13. reverse():
Mutates the original array by reversing it.
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.reverse()); // [5, 4, 3, 2, 1]
14. concat():
Merges the multiple arrays.
let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]
15. fill():
Replace the array elements.
let arr = [1, 2, 3, 4, 5];
// Fill with 0 from index 1 to 3
arr.fill(0, 1, 4);
console.log(arr); // [1, 0, 0, 0, 5]
16. indexOf() & lastIndexOf():
Helps to find the position of element in the array.
indexOf()
: Finds the first occurrence of an element.lastIndexOf()
: Finds the last occurrence of an element.
let numbers = [10, 20, 30, 10, 40];
console.log(numbers.indexOf(10)); // 0
console.log(numbers.lastIndexOf(10)); // 3
17. values():
Returns an iterator containing the values of the array.
let fruits = ["apple", "banana", "cherry"];
let values = fruits.values();
for (let value of values) {
console.log(value); // apple, banana, cherry
}
18. every():
checks if all elements in the array pass the conditions.
let scores = [90, 85, 88, 92];
let allPassed = scores.every(score => score >= 80);
console.log(allPassed); // true
19. keys():
Returns an iterator containing the keys (indexes) of the array.
let fruits = ["apple", "banana"];
let keys = fruits.keys();
for (let key of keys) {
console.log(key); // 0, 1
}
💬 Which array method is your favorite? Let’s discuss in the comments! 🚀
Thank you for reading. Before you go 🙋♂️:
Please clap for the writer ️️️
🏌️Follow me: https://medium.com/@sandeeppant