Best JavaScript Array Methods (With Examples)
Best JavaScript Array Methods (With Examples)
Last Updated: 08 Jul, 2024
JavaScript provides powerful array methods that help developers add, remove, modify, and manipulate data efficiently. Mastering these methods will make your code cleaner and more efficient.
📌 Table of Contents
- Array some() Method
- Array reduce() Method
- Array map() Method
- Array every() Method
- Array flat() Method
- Array flatMap() Method
- Array filter() Method
- Array findIndex() Method
- Array find() Method
- Array fill() Method
- Array forEach() Method
- Array sort() Method
- Array concat() Method
- Array includes() Method
- Array reverse() Method
🔹 1. Array some() Method
The some()
method checks if at least one element in the array meets a given condition.
✅ Example:
let array = [2, 5, 8, 1, 4];
console.log(array.some(num => num > 5));
🖥 Output:
true
🔹 2. Array reduce() Method
The reduce()
method reduces an array to a single value.
✅ Example:
let numbers = [88, 50, 25, 10];
let result = numbers.reduce((total, num) => total - num);
console.log(result);
🖥 Output:
3
🔹 3. Array map() Method
The map()
method creates a new array by applying a function to each element.
✅ Example:
let numbers = [4, 9, 16, 25];
let squared = numbers.map(num => Math.sqrt(num));
console.log(squared);
🖥 Output:
[2, 3, 4, 5]
🔹 4. Array every() Method
The every()
method checks if all elements in the array meet a condition.
✅ Example:
let arr = [11, 89, 23, 7, 98];
let allPositive = arr.every(num => num > 0);
console.log(allPositive);
🖥 Output:
true
🔹 5. Array flat() Method
The flat()
method flattens nested arrays into a single array.
✅ Example:
let arr = [[11, 89], [23, 7], 98];
let flatArray = arr.flat();
console.log(flatArray);
🖥 Output:
[11, 89, 23, 7, 98]
🔹 6. Array flatMap() Method
The flatMap()
method maps and then flattens an array.
✅ Example:
let myArray = [[1], [2], [3], [4], [5]];
let result = myArray.flatMap(num => num * 10);
console.log(result);
🖥 Output:
[10, 20, 30, 40, 50]
🔹 7. Array filter() Method
The filter()
method creates a new array with elements that match a condition.
✅ Example:
let numbers = [112, 52, 0, -1, 944];
let filtered = numbers.filter(num => num > 0);
console.log(filtered);
🖥 Output:
[112, 52, 944]
📌 More Methods Coming Soon...
Stay tuned for more detailed explanations and examples of JavaScript array methods.
🚀 Subscribe for the latest updates and JavaScript tips!
Leave a Comment