JavaScript Arrays: Complete Guide with Methods and Examples
Master JavaScript arrays with this comprehensive guide. Learn array methods, manipulation techniques, iteration patterns, and best practices.
JavaScript Arrays: Complete Guide with Methods and Examples
Arrays are one of the most fundamental data structures in JavaScript. They allow you to store multiple values in a single variable and provide powerful methods for manipulation and transformation. This guide covers everything you need to know about JavaScript arrays.
What is an Array?
An array is an ordered collection of values. Each value is called an element, and each element has a numeric position called an index.
// Creating arrays
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, 'hello', true, null, { name: 'John' }];
// Accessing elements
console.log(fruits[0]); // 'apple'
console.log(fruits[1]); // 'banana'
console.log(fruits[2]); // 'orange'
Creating Arrays
There are multiple ways to create arrays in JavaScript:
// Array literal (recommended)
const arr1 = [1, 2, 3];
// Array constructor
const arr2 = new Array(1, 2, 3);
// Creating empty array
const empty1 = [];
const empty2 = new Array();
// Creating array with specific length
const arr3 = new Array(5); // Creates array with 5 empty slots
// Array.from() - create array from iterable
const arr4 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
const arr5 = Array.from([1, 2, 3], (x) => x * 2); // [2, 4, 6]
// Array.of() - create array from arguments
const arr6 = Array.of(1, 2, 3); // [1, 2, 3]
const arr7 = Array.of(7); // [7] (not array with length 7)
Array Properties
Length Property
The length
property returns the number of elements in an array:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.length); // 3
// Modifying length
fruits.length = 2; // Removes elements
console.log(fruits); // ['apple', 'banana']
fruits.length = 5; // Adds empty slots
console.log(fruits); // ['apple', 'banana', empty × 3]
Basic Array Methods
Adding Elements
const arr = [1, 2, 3];
// push() - add to end
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
// unshift() - add to beginning
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3, 4]
// Using index
arr[5] = 5;
console.log(arr); // [0, 1, 2, 3, 4, 5]
Removing Elements
const arr = [1, 2, 3, 4, 5];
// pop() - remove from end
const last = arr.pop();
console.log(last); // 5
console.log(arr); // [1, 2, 3, 4]
// shift() - remove from beginning
const first = arr.shift();
console.log(first); // 1
console.log(arr); // [2, 3, 4]
// delete - removes element but leaves hole
delete arr[1];
console.log(arr); // [2, empty, 4]
splice() - Swiss Army Knife
The splice()
method can add, remove, or replace elements:
const arr = [1, 2, 3, 4, 5];
// Remove elements
arr.splice(2, 2); // From index 2, remove 2 elements
console.log(arr); // [1, 2, 5]
// Add elements
arr.splice(2, 0, 3, 4); // At index 2, remove 0, add 3 and 4
console.log(arr); // [1, 2, 3, 4, 5]
// Replace elements
arr.splice(1, 2, 'a', 'b'); // At index 1, remove 2, add 'a' and 'b'
console.log(arr); // [1, 'a', 'b', 4, 5]
slice() - Extract Portion
const arr = [1, 2, 3, 4, 5];
// Extract portion (doesn't modify original)
const portion1 = arr.slice(1, 4); // From index 1 to 3
console.log(portion1); // [2, 3, 4]
const portion2 = arr.slice(2); // From index 2 to end
console.log(portion2); // [3, 4, 5]
const portion3 = arr.slice(-2); // Last 2 elements
console.log(portion3); // [4, 5]
// Copy entire array
const copy = arr.slice();
Array Transformation Methods
map() - Transform Elements
Creates a new array by transforming each element:
const numbers = [1, 2, 3, 4, 5];
// Double each number
const doubled = numbers.map((x) => x * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// With index
const indexed = numbers.map((val, index) => `${index}: ${val}`);
console.log(indexed); // ['0: 1', '1: 2', '2: 3', '3: 4', '4: 5']
// Transform objects
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
];
const names = users.map((user) => user.name);
console.log(names); // ['John', 'Jane']
filter() - Select Elements
Creates a new array with elements that pass a test:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Get even numbers
const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]
// Filter objects
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
const adults = users.filter((user) => user.age >= 30);
console.log(adults); // [{ name: 'John', age: 30 }, { name: 'Bob', age: 35 }]
// Chain with map
const adultNames = users
.filter((user) => user.age >= 30)
.map((user) => user.name);
console.log(adultNames); // ['John', 'Bob']
reduce() - Aggregate Values
Reduces array to a single value:
const numbers = [1, 2, 3, 4, 5];
// Sum all numbers
const sum = numbers.reduce((acc, val) => acc + val, 0);
console.log(sum); // 15
// Find maximum
const max = numbers.reduce((max, val) => (val > max ? val : max));
console.log(max); // 5
// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // { apple: 3, banana: 2, orange: 1 }
// Flatten array
const nested = [
[1, 2],
[3, 4],
[5, 6],
];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
console.log(flat); // [1, 2, 3, 4, 5, 6]
Searching and Finding
indexOf() and lastIndexOf()
const arr = [1, 2, 3, 2, 1];
console.log(arr.indexOf(2)); // 1 (first occurrence)
console.log(arr.lastIndexOf(2)); // 3 (last occurrence)
console.log(arr.indexOf(5)); // -1 (not found)
// With fromIndex
console.log(arr.indexOf(2, 2)); // 3 (search from index 2)
includes()
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(6)); // false
// With NaN
const arrWithNaN = [1, 2, NaN];
console.log(arrWithNaN.includes(NaN)); // true (indexOf can't find NaN)
find() and findIndex()
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
];
// Find first matching element
const user = users.find((u) => u.name === 'Jane');
console.log(user); // { id: 2, name: 'Jane' }
// Find index of first matching element
const index = users.findIndex((u) => u.name === 'Jane');
console.log(index); // 1
// Find with complex condition
const adult = users.find((u) => u.age >= 18);
Iteration Methods
forEach()
const arr = ['a', 'b', 'c'];
// Basic iteration
arr.forEach((item) => console.log(item));
// With index and array
arr.forEach((item, index, array) => {
console.log(`${index}: ${item} in [${array}]`);
});
// Cannot break out of forEach
// Use for...of or traditional for loop if you need to break
for...of Loop
const arr = ['a', 'b', 'c'];
// Iterate values
for (const value of arr) {
console.log(value);
}
// With index using entries()
for (const [index, value] of arr.entries()) {
console.log(`${index}: ${value}`);
}
// Can use break/continue
for (const value of arr) {
if (value === 'b') break;
console.log(value);
}
Testing Arrays
every() and some()
const numbers = [2, 4, 6, 8, 10];
// Test if all elements pass
const allEven = numbers.every((x) => x % 2 === 0);
console.log(allEven); // true
// Test if at least one passes
const hasLarge = numbers.some((x) => x > 5);
console.log(hasLarge); // true
// Practical example
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
const allAdults = users.every((user) => user.age >= 18);
const hasYoung = users.some((user) => user.age < 30);
Sorting and Reversing
sort()
// Default sort (alphabetical)
const fruits = ['banana', 'apple', 'orange'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'orange']
// Number sorting (need compare function)
const numbers = [10, 5, 40, 25, 1000, 1];
numbers.sort(); // Wrong: ['1', '10', '1000', '25', '40', '5']
// Correct number sorting
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers); // [1, 5, 10, 25, 40, 1000]
numbers.sort((a, b) => b - a); // Descending
console.log(numbers); // [1000, 40, 25, 10, 5, 1]
// Sort objects
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
users.sort((a, b) => a.age - b.age);
console.log(users); // Sorted by age
// Case-insensitive string sort
const names = ['john', 'Jane', 'bob', 'Alice'];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
reverse()
const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]
// Reverse without modifying original
const reversed = [...arr].reverse();
Joining and Concatenating
join()
const arr = ['Hello', 'World', '!'];
console.log(arr.join()); // 'Hello,World,!'
console.log(arr.join(' ')); // 'Hello World !'
console.log(arr.join('-')); // 'Hello-World-!'
console.log(arr.join('')); // 'HelloWorld!'
concat()
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
// Concatenate arrays
const combined = arr1.concat(arr2, arr3);
console.log(combined); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Original arrays unchanged
console.log(arr1); // [1, 2, 3]
// Can also add individual values
const extended = arr1.concat(4, 5, [6, 7]);
console.log(extended); // [1, 2, 3, 4, 5, 6, 7]
Modern Array Methods
flat() and flatMap()
// flat() - flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log(nested.flat(Infinity)); // Flatten all levels
// flatMap() - map then flatten
const sentences = ['Hello World', 'How are you'];
const words = sentences.flatMap((sentence) => sentence.split(' '));
console.log(words); // ['Hello', 'World', 'How', 'are', 'you']
// Practical example
const users = [
{ name: 'John', hobbies: ['reading', 'gaming'] },
{ name: 'Jane', hobbies: ['cooking', 'dancing'] },
];
const allHobbies = users.flatMap((user) => user.hobbies);
console.log(allHobbies); // ['reading', 'gaming', 'cooking', 'dancing']
Array.from() Advanced Usage
// Create array from array-like objects
const nodeList = document.querySelectorAll('div');
const divArray = Array.from(nodeList);
// With mapping function
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(numbers); // [1, 2, 3, 4, 5]
// Create range
const range = Array.from({ length: 10 }, (_, i) => i * 2);
console.log(range); // [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
// Convert Set to Array
const uniqueNumbers = Array.from(new Set([1, 2, 2, 3, 3, 4]));
console.log(uniqueNumbers); // [1, 2, 3, 4]
Array Destructuring
// Basic destructuring
const arr = [1, 2, 3, 4, 5];
const [first, second] = arr;
console.log(first, second); // 1 2
// Skip elements
const [, , third] = arr;
console.log(third); // 3
// Rest elements
const [head, ...tail] = arr;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// Default values
const [a, b, c = 0] = [1, 2];
console.log(c); // 0
// Swapping variables
let x = 1,
y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
// Function returns
function getCoordinates() {
return [10, 20];
}
const [x1, y1] = getCoordinates();
Common Array Patterns
Remove Duplicates
const numbers = [1, 2, 2, 3, 3, 4, 5, 5];
// Using Set
const unique1 = [...new Set(numbers)];
console.log(unique1); // [1, 2, 3, 4, 5]
// Using filter with indexOf
const unique2 = numbers.filter(
(item, index) => numbers.indexOf(item) === index
);
// Remove duplicate objects
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'Bob' },
];
const uniqueUsers = users.filter(
(user, index, self) => index === self.findIndex((u) => u.id === user.id)
);
Array Shuffling
function shuffle(array) {
const arr = [...array]; // Copy array
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
const numbers = [1, 2, 3, 4, 5];
console.log(shuffle(numbers)); // [3, 1, 5, 2, 4] (random order)
Grouping Array Elements
// Group by property
const people = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Jane', age: 25, city: 'Boston' },
{ name: 'Bob', age: 35, city: 'New York' },
{ name: 'Alice', age: 28, city: 'Boston' },
];
const groupedByCity = people.reduce((groups, person) => {
const city = person.city;
if (!groups[city]) groups[city] = [];
groups[city].push(person);
return groups;
}, {});
console.log(groupedByCity);
// {
// 'New York': [{ name: 'John', ... }, { name: 'Bob', ... }],
// 'Boston': [{ name: 'Jane', ... }, { name: 'Alice', ... }]
// }
Performance Tips
- Use appropriate methods:
for
loops are fastest for simple iterations - Avoid modifying array length in loops
- Pre-allocate array size when possible
- Use
Array.from()
for array-like objects - Consider using typed arrays for numeric data
// Performance comparison
const size = 1000000;
const arr = Array.from({ length: size }, (_, i) => i);
// Fastest: for loop
console.time('for');
let sum1 = 0;
for (let i = 0; i < arr.length; i++) {
sum1 += arr[i];
}
console.timeEnd('for');
// Slower: forEach
console.time('forEach');
let sum2 = 0;
arr.forEach((n) => (sum2 += n));
console.timeEnd('forEach');
// Slowest but most functional: reduce
console.time('reduce');
const sum3 = arr.reduce((a, b) => a + b, 0);
console.timeEnd('reduce');
Best Practices
- Use const for arrays - You can still modify contents
- Prefer array methods over loops - More readable and functional
- Avoid sparse arrays - Arrays with holes can cause issues
- Use appropriate data structures - Consider Set, Map for specific use cases
- Be careful with mutation - Many methods modify the original array
Conclusion
JavaScript arrays are incredibly powerful and versatile. Key takeaways:
- Arrays can hold any type of data
- Rich set of built-in methods for manipulation
- Functional methods like map, filter, reduce enable clean code
- Understanding mutation vs. immutability is crucial
- Modern features like destructuring and spread operator simplify code
Master these array concepts and methods to write more efficient JavaScript code!