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

LeetCode
Understanding: Keys and Rooms (LeetCode 841)
November 20, 2025
1 min
Β© 2025, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube