Array Methods
Array Methods
Adding/Removing Elements
const arr = [1, 2, 3];
// End
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
// Beginning
arr.unshift(0); // [0, 1, 2, 3]
arr.shift(); // [1, 2, 3]
// Splice (anywhere)
arr.splice(1, 1); // Remove at index 1: [1, 3]
arr.splice(1, 0, 1.5); // Insert at index 1: [1, 1.5, 3]
Finding Elements
const arr = [1, 2, 3, 4, 5];
arr.indexOf(3); // 2 (index)
arr.includes(3); // true
arr.find(x => x > 3); // 4 (first match)
arr.findIndex(x => x > 3); // 3 (index of first match)
Sorting
const arr = [3, 1, 4, 1, 5, 9];
// Sort (mutates!)
arr.sort(); // [1, 1, 3, 4, 5, 9]
arr.sort((a, b) => b - a); // Descending
// Reverse (mutates!)
arr.reverse(); // [9, 5, 4, 3, 1]
// Non-mutating sort
const sorted = [...arr].sort((a, b) => a - b);
Join and Split
const arr = ['a', 'b', 'c'];
arr.join('-'); // "a-b-c"
const str = 'a-b-c';
str.split('-'); // ['a', 'b', 'c']
Slice vs Splice
// Slice (non-mutating)
const arr = [1, 2, 3, 4, 5];
arr.slice(1, 3); // [2, 3]
arr.slice(-2); // [4, 5]
// Splice (mutating)
arr.splice(1, 2); // Removes [2, 3], arr is now [1, 4, 5]
Concat
const arr1 = [1, 2];
const arr2 = [3, 4];
arr1.concat(arr2); // [1, 2, 3, 4]
[...arr1, ...arr2]; // [1, 2, 3, 4]
Iteration Methods
Iteration Methods
forEach
const arr = [1, 2, 3];
arr.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// 0: 1
// 1: 2
// 2: 3
map
const arr = [1, 2, 3];
const doubled = arr.map(x => x * 2);
console.log(doubled); // [2, 4, 6]
filter
const arr = [1, 2, 3, 4, 5];
const evens = arr.filter(x => x % 2 === 0);
console.log(evens); // [2, 4]
reduce
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15
// Building object
const arr = ['a', 'b', 'a', 'c', 'b'];
const count = arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
console.log(count); // { a: 2, b: 2, c: 1 }
some and every
const arr = [1, 2, 3, 4, 5];
arr.some(x => x > 3); // true (at least one)
arr.every(x => x > 0); // true (all)
find
const arr = [1, 2, 3, 4, 5];
const found = arr.find(x => x > 3);
console.log(found); // 4
flat
const arr = [1, [2, 3], [4, [5]]];
arr.flat(); // [1, 2, 3, 4, [5]]
arr.flat(2); // [1, 2, 3, 4, 5]
arr.flat(Infinity); // [1, 2, 3, 4, 5]
flatMap
const arr = [1, 2, 3];
const result = arr.flatMap(x => [x, x * 2]);
console.log(result); // [1, 2, 2, 4, 3, 6]
Array Transformations
Array Transformations
Method Chaining
const result = [1, 2, 3, 4, 5]
.filter(x => x % 2 !== 0)
.map(x => x * 2)
.reduce((acc, x) => acc + x, 0);
console.log(result); // 18
Building Data Structures
// Group by
const arr = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 30 }
];
const grouped = arr.reduce((acc, person) => {
const key = person.age;
acc[key] = acc[key] || [];
acc[key].push(person);
return acc;
}, {});
// { 30: [...], 25: [...] }
Deduplication
const arr = [1, 2, 2, 3, 3, 4];
// Using Set
const unique = [...new Set(arr)]; // [1, 2, 3, 4]
// Using filter
const unique2 = arr.filter((item, index) =>
arr.indexOf(item) === index
);
Partitioning
function partition(arr, predicate) {
return arr.reduce(([pass, fail], item) => {
return predicate(item)
? [[...pass, item], fail]
: [pass, [...fail, item]];
}, [[], []]);
}
const arr = [1, 2, 3, 4, 5];
const [evens, odds] = partition(arr, x => x % 2 === 0);
// evens: [2, 4], odds: [1, 3, 5]
Array.from
// From string
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
// With mapping
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
// From Set
Array.from(new Set([1, 2, 3])); // [1, 2, 3]
Destructuring with Arrays
const arr = [1, 2, 3, 4, 5];
const [first, second, ...rest] = arr;
// first: 1, second: 2, rest: [3, 4, 5]
const [, , third] = arr;
// third: 3
const [a, , c] = arr;
// a: 1, c: 3
Performance Tips
// Avoid in loops
for (let i = 0; i < arr.length; i++) { } // Good
arr.forEach(item => { }); // Slower
// Use for...of for readability
for (const item of arr) { } // Good
// Chain carefully (creates intermediate arrays)
const result = arr
.filter(x => x > 0)
.map(x => x * 2); // Creates new array
Practice Problems
Create a reusable React component implementing JavaScript Arrays. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for JavaScript Arrays using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize JavaScript Arrays for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the difference between slice and splice?
2. What does reduce() return?
3. Which method creates a new array with transformed elements?
4. What does filter() return?
5. How do you remove duplicates from an array?
Flashcards
Question
What is the difference between map and filter?
Click to reveal answer
Answer
map transforms each element. filter keeps elements that pass a test.
Question
What does reduce() do?
Click to reveal answer
Answer
Accumulates array elements into a single value using a callback function.
Question
What is the difference between slice and splice?
Click to reveal answer
Answer
slice is non-mutating (creates new array). splice mutates the original array.
Question
How do you flatten a nested array?
Click to reveal answer
Answer
Use arr.flat(depth) or arr.flat(Infinity) to flatten completely.
Question
What is method chaining?
Click to reveal answer
Answer
Calling multiple array methods in sequence: arr.filter().map().reduce()
Revision Notes
Key Takeaways
- 1.map transforms, filter selects, reduce accumulates
- 2.splice mutates, slice does not
- 3.Method chaining enables clean transformations
- 4.Use Set for deduplication
- 5.forEach doesn't return a value
Interview Tips
- •Know the difference between slice and splice
- •Be able to use map, filter, and reduce
- •Understand method chaining
- •Know how to flatten and deduplicate arrays
Cheat Sheet
Array Methods Cheat Sheet
Mutating Methods
push/pop, shift/unshift, splice, sort, reverse, fill
Non-Mutating Methods
slice, concat, flat, map, filter, reduce, find, includes, indexOf
Iteration Methods
forEach, map, filter, reduce, some, every, find, findIndex
Transformation Methods
map, filter, reduce, flat, flatMap, sort, reverse, slice
Creating Arrays
const arr = [1, 2, 3];
Array.from('hello');
Array.from({ length: 5 }, (_, i) => i);
Method Chaining
arr.filter(x => x > 0).map(x => x * 2).reduce((a, b) => a + b, 0);