Js Array Methods in JavaScript
? JavaScript Array Methods
JavaScript arrays come packed with lots of handy methods for manipulating, transforming, and querying arrays.
Commonly Used Array Methods
| Method | Description | Example |
|---|---|---|
.push(item) | Add item(s) to end | arr.push(4) |
.pop() | Remove last item and return it | arr.pop() |
.shift() | Remove first item and return it | arr.shift() |
.unshift(item) | Add item(s) to start | arr.unshift(0) |
.concat(arr2) | Merge arrays, return new array | arr.concat([4,5]) |
.slice(start, end) | Extract a portion, return new array | arr.slice(1,3) |
.splice(start, deleteCount, items...) | Add/remove items at position | arr.splice(2,1,"a","b") |
.indexOf(item) | Find index of item (or -1 if not found) | arr.indexOf(3) |
.includes(item) | Check if array contains item (true/false) | arr.includes(3) |
.forEach(fn) | Run function on each element | arr.forEach(x => console.log(x)) |
.map(fn) | Return new array by transforming each element | arr.map(x => x * 2) |
.filter(fn) | Return new array with elements passing test | arr.filter(x => x > 2) |
.reduce(fn, init) | Accumulate array to single value | arr.reduce((sum, x) => sum + x, 0) |
.sort(fn) | Sort elements in place (default lexicographic) | arr.sort((a,b) => a - b) |
.reverse() | Reverse array elements in place | arr.reverse() |
.join(separator) | Join array to string | arr.join(", ") |
Example Usage
const numbers = [1, 2, 3, 4, 5];// Add item to endnumbers.push(6); // [1,2,3,4,5,6]// Remove first itemnumbers.shift(); // [2,3,4,5,6]// Map: double each numberconst doubled = numbers.map(x => x * 2); // [4,6,8,10,12]// Filter: only even numbersconst evens = numbers.filter(x => x % 2 === 0); // [2,4,6]// Reduce: sum all numbersconst sum = numbers.reduce((acc, val) => acc + val, 0); // 20console.log({numbers, doubled, evens, sum});Notes
Many methods like
.map(),.filter(), and.reduce()return new arrays or values — they do not modify the original array.Methods like
.push(),.pop(),.shift(),.unshift(),.splice(),.sort(), and.reverse()modify the original array.
Want me to help with deep dive into any specific array method or examples combining multiple array methods?