Data Structures - Arrays in JavaScript
Data Structures - Arrays in JavaScript
Arrays in JavaScript
Reading Material
Topics Covered
Iterating over Array
Remapping Array
Filtering Array
Reducing Array
Sorting Array
Destructurin
Flattening Array
Removing Duplicates from an Arra
Solving: Two Sum (Leetcode - 1
Solving: Intersection of Two Arrays (Leetcode - 350
Solving: Move Zeroes (Leetcode 283
Solving: Maximum Product Subarray (Leetcode 152)
Arrays are one of the fundamental data structures in JavaScript. They are used to store multiple values in a
single variable, allowing for efficient data manipulation and retrieval.
The traditional for loop offers complete control over the iteration process, including the ability to skip elements
or break the loop early.
console.log(array[i]);
The for...of loop provides a simpler syntax for iterating over iterable objects, including arrays, and is especially
useful when you don't need the index of the elements.
console.log(value);
The forEach method executes a provided function once for each array element. It's a functional approach to
iteration.
array.forEach(value => {
console.log(value);
});
PW Skills
Using map Method for Iteration:
While map is typically used for remapping arrays, it can also be used for iteration if you're creating a new array
based on the original one.
array.map(value => {
console.log(value);
});
2. Remapping Arrays
Remapping arrays involves transforming each element of an array to create a new array.
The map method is a common way to remap arrays. It applies a function to each element of the array and
returns a new array with the results.
T his method is useful for applying transformations, such as converting all strings in an array to uppercase:
3. Filtering Arrays
Filtering arrays allows you to create a new array with only the elements that pass a specified condition.
The filter method applies a function to each element of the array and includes it in the new array if the function
returns true.
console.log(evenNumbers); // [2, 4]
Filtering is useful for creating subsets of arrays based on certain criteria, such as removing null values from an
array:
PW Skills
let values = [1, null, 2, undefined, 3, null, 4];
console.log(nonNullValues); // [1, 2, 3, 4]
4. Reducing Arrays
Reducing arrays involves combining all elements of an array into a single value.
The reduce method applies a function to each element of the array (from left to right) to reduce the array to a
single value.
Reducing arrays involves combining all elements of an array into a single value.
The reduce method applies a function to each element of the array (from left to right) to reduce the array to a
single value.
console.log(sum); // 15
reduce is versatile and can be used for various operations such as finding the ma imum value in an array
, x :
}, -Infinity);
console.log(max); // 5
5. Sorting Arrays
Sorting arrays involves arranging the elements in a specified order.
The sort method sorts the elements of an array in place and returns the sorted array. y default sort converts
B ,
numbers.sort();
PW Skills
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 5, 8]
6. Destructuring
Destructuring allows for easy extraction of values from arrays and objects.
Array Destructuring:
You can unpack values from arrays into distinct variables using array destructuring.
console.log(first); // 1
console.log(second); // 2
console.log(third); // 3
console.log(a); // 1
console.log(b); // 10
console.log(c); // 4
console.log(d); // 5
console.log(e); // 6
7. Flattening Arrays
Flattening arrays involves converting a multi-dimensional array into a single-dimensional array.
The flat method creates a new array with all sub-array elements concatenated into it recursively up to the
specified depth.
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
PW Skills
You can specify the depth to which the array should be flattened:
Using Set:
The Set object stores unique values of any type, whether primitive values or object references.
console.log(uniqueArray); // [1, 2, 3, 4, 5]
console.log(uniqueArrayWithFilter); // [1, 2, 3, 4, 5]
Approach
Use a simple nested loop to check every possible pair of elements
If a pair adds up to the target, return their indices.
Complexity
Time Complexity: O(n^2), where n is the number of elements in the array. We check every pair of elements
Space Complexity: O(1). We do not use any extra space.
return [];
PW Skills
10. Solving: Intersection of Two Arrays
(Leetcode - 350)
Problem Statement: Given two integer arrays nums1 and nums2, return an array of their intersection. Each
element in the result must appear as many times as it shows in both arrays.
Approach
Use a simple nested loop to check every possible pair of elements from nums1 and nums2
If an element in nums1 matches an element in nums2, add the element to the result array and remove it
from nums2 to avoid counting it multiple times
Continue checking for other elements.
Complexity
Time Complexity: O(n * m), where n is the number of elements in nums1 and m is the number of elements in
nums2. We check every pair of elements
Space Complexity: O(n), where n is the size of the result array in the worst case.
result.push(nums1[i]);
return result;
Approach
Use a two-pointer technique
One pointer keeps track of the position to place the next non-zero element
Iterate through the array, and when a non-zero element is found, swap it with the element at the position of
the first pointer
After all elements are processed, the zeros will be moved to the end.
Complexity
Time Complexity: O(n), where n is the number of elements in the array. We iterate through the array once
Space Complexity: O(1). We do not use any extra space.
PW Skills
function moveZeroes(nums) {
let lastNonZeroFoundAt = 0;
if (nums[i] !== 0) {
lastNonZeroFoundAt++;
return nums;
(Leetcode 152)
Problem Statement: Given an integer array nums, find the contiguous subarray within an array (containing at
least one number) which has the largest product.
Approach
Use two variables to keep track of the maximum product and the minimum product up to the current
position
For each element in the array, update the maximum and minimum products considering the current
element
The result is the maximum value found among these products.
Complexity
Time Complexity: O(n), where n is the number of elements in the array. We iterate through the array once
Space Complexity: O(1). We use a constant amount of extra space.
function maxProduct(nums) {
maxSoFar = tempMax;
return result;
PW Skills