Arrays are one of the most commonly used data structures in JavaScript. They help store and manage collections of data β whether itβs a list of numbers, strings, or even objects.
An array is a special variable that can hold more than one value at a time.
const fruits = ["apple", "banana", "cherry"];
JavaScript arrays are zero-indexed, meaning the first element has index 0
.
console.log(fruits[0]); // 'apple'
Method | Description |
---|---|
push() | Adds item to the end |
pop() | Removes the last item |
shift() | Removes the first item |
unshift() | Adds item to the beginning |
splice() | Adds/removes items at a specific index |
slice() | Returns a copy of a section |
forEach() | Executes a function on each array element |
map() | Transforms array items into a new array |
filter() | Filters array based on condition |
reduce() | Reduces array to a single value |
const nums = [1, 2, 3, 4, 5];for (let i = 0; i < nums.length; i++) {console.log(nums[i]);}// or with for...offor (const num of nums) {console.log(num);}
function removeDuplicates(arr) {return [...new Set(arr)];}console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));// Output: [1, 2, 3, 4]
LeetCode Problem: 1. Two Sum
var twoSum = function(nums, target) {const map = new Map();for (let i = 0; i < nums.length; i++) {const complement = target - nums[i];if (map.has(complement)) {return [map.get(complement), i];}map.set(nums[i], i);}return [];};// Example:console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]
This example showcases how arrays can be combined with maps to solve algorithmic problems efficiently.
Arrays are fundamental in JavaScript and serve as the building blocks for handling ordered collections of data. Mastering their methods and usage is essential for any JavaScript developer.
π Pro Tip: Practice transforming, filtering, and reducing arrays to get comfortable with functional programming in JavaScript.
Quick Links
Legal Stuff
Social Media