Home
JavaScript
๐Ÿ“š JavaScript Arrays: The Essential Guide
April 07, 2024
1 min

Table Of Contents

01
๐Ÿš€ What Is an Array?
02
โœจ Common Array Methods
03
๐Ÿ” Looping Through Arrays
04
๐Ÿงช Real-World Example: Remove Duplicates
05
๐Ÿงฉ LeetCode Example: Two Sum
06
๐Ÿ”š Final Thoughts

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.


๐Ÿš€ What Is an Array?

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'

โœจ Common Array Methods

MethodDescription
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

๐Ÿ” Looping Through Arrays

const nums = [1, 2, 3, 4, 5];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
// or with for...of
for (const num of nums) {
console.log(num);
}

๐Ÿงช Real-World Example: Remove Duplicates

function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));
// Output: [1, 2, 3, 4]

๐Ÿงฉ LeetCode Example: Two Sum

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.


๐Ÿ”š Final Thoughts

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.


Tags

#Javascript

Share

Related Posts

Debounce in JavaScript
Debounce in JavaScript
August 30, 2025
1 min
ยฉ 2025, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube