Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Data Structures - Arrays in JavaScript

Uploaded by

Subhankar Jena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Data Structures - Arrays in JavaScript

Uploaded by

Subhankar Jena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Data Structures

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.

1. Iterating Over Arrays


Iteration allows you to access each element of an array. Here are several ways to iterate over arrays in
JavaScript:

Using for Loop:

The traditional for loop offers complete control over the iteration process, including the ability to skip elements
or break the loop early.

let array = [1, 2, 3, 4, 5];

for (let i = 0; i < array.length; i++) {

console.log(array[i]);

Using for...of Loop:

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.

for (let value of array) {

console.log(value);

Using forEach Method:

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);

return value; // To keep the functionality of map, we


must return a value

});

2. Remapping Arrays
Remapping arrays involves transforming each element of an array to create a new array.

Using map Method:

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.

let numbers = [1, 2, 3, 4, 5];

let squaredNumbers = numbers.map(number => number *


number);

console.log(squaredNumbers); // [1, 4, 9, 16, 25]

T his method is useful for applying transformations, such as converting all strings in an array to uppercase:

let strings = ["hello", "world"];

let upperCaseStrings = strings.map(str =>


str.toUpperCase());

console.log(upperCaseStrings); // ["HELLO", "WORLD"]

3. Filtering Arrays
Filtering arrays allows you to create a new array with only the elements that pass a specified condition.

Using filter Method:

The filter method applies a function to each element of the array and includes it in the new array if the function

returns true.

let numbers = [1, 2, 3, 4, 5];

let evenNumbers = numbers.filter(number => number % 2 ===


0);

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];

let nonNullValues = values.filter(value => value !== null


&& value !== undefined);

console.log(nonNullValues); // [1, 2, 3, 4]

4. Reducing Arrays
Reducing arrays involves combining all elements of an array into a single value.

Using reduce Method:

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.

Using reduce Method:

The reduce method applies a function to each element of the array (from left to right) to reduce the array to a
single value.

let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce((accumulator, currentValue) =>


accumulator + currentValue, 0);

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 :

let max = numbers.reduce((accumulator, currentValue) => {

return Math.max(accumulator, currentValue);

}, -Infinity);

console.log(max); // 5

5. Sorting Arrays
Sorting arrays involves arranging the elements in a specified order.

Using sort Method:

The sort method sorts the elements of an array in place and returns the sorted array. y default sort converts
B ,

the elements into strings and sorts them le icographically.


x

let numbers = [5, 3, 8, 1, 2];

numbers.sort();

console.log(numbers); // [1, 2, 3, 5, 8] (lexicographical


order, not numerical)

To sort numbers correctly a compare function should be provided


, :

PW Skills
numbers.sort((a, b) => a - b);

console.log(numbers); // [1, 2, 3, 5, 8]

Sorting strings or objects can also be customized using a compare function:

let fruits = ["banana", "apple", "cherry"];

fruits.sort((a, b) => a.localeCompare(b));

console.log(fruits); // ["apple", "banana", "cherry"]

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.

let [first, second, third] = [1, 2, 3];

console.log(first); // 1

console.log(second); // 2

console.log(third); // 3

Destructuring can also handle default values and nested arrays:

let [a, b = 10] = [1];

console.log(a); // 1

console.log(b); // 10

let [c, [d, e]] = [4, [5, 6]];

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.

Using flat Method:

The flat method creates a new array with all sub-array elements concatenated into it recursively up to the
specified depth.

let nestedArray = [1, [2, 3], [4, [5, 6]]];

let flatArray = nestedArray.flat(2);

console.log(flatArray); // [1, 2, 3, 4, 5, 6]

PW Skills
You can specify the depth to which the array should be flattened:

let partiallyFlattenedArray = nestedArray.flat(1);

console.log(partiallyFlattenedArray); // [1, 2, 3, 4, [5,


6]]

8. Removing Duplicates from an Array


Removing duplicates involves creating a new array with only unique elements.

Using Set:

The Set object stores unique values of any type, whether primitive values or object references.

let array = [1, 2, 2, 3, 4, 4, 5];

let uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 4, 5]

Using filter and indexOf:

Another method to remove duplicates is using filter combined with indexOf.

let uniqueArrayWithFilter = array.filter((value, index,


self) => self.indexOf(value) === index);

console.log(uniqueArrayWithFilter); // [1, 2, 3, 4, 5]

9. Solving: Two Sum (Leetcode - 1)


Problem Statement: Given an array of integers nums and an integer target, return indices of the two numbers
such that they add up to target.

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.

function twoSum(nums, target) {

for (let i = 0; i < nums.length; i++) {

for (let j = i + 1; j < nums.length; j++) {

if (nums[i] + nums[j] === target) {

return [i, j];

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.

function intersect(nums1, nums2) {

const result = [];

for (let i = 0; i < nums1.length; i++) {

for (let j = 0; j < nums2.length; j++) {

if (nums1[i] === nums2[j]) {

result.push(nums1[i]);

nums2.splice(j, 1); // Remove the element from


nums2

break; // Move to the next element in nums1

return result;

11. Solving: Move Zeroes (Leetcode 283)


Problem Statement: Given an array nums, write a function to move all 0s to the end of it while maintaining the
relative order of the non-zero elements.

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;

for (let i = 0; i < nums.length; i++) {

if (nums[i] !== 0) {

[nums[lastNonZeroFoundAt], nums[i]] = [nums[i],


nums[lastNonZeroFoundAt]];

lastNonZeroFoundAt++;

return nums;

12. Solving: Maximum Product Subarray

(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) {

let maxSoFar = nums[0];

let minSoFar = nums[0];

let result = nums[0];

for (let i = 1; i < nums.length; i++) {

let current = nums[i];

let tempMax = Math.max(current, maxSoFar * current,


minSoFar * current);

minSoFar = Math.min(current, maxSoFar * current,


minSoFar * current);

maxSoFar = tempMax;

result = Math.max(result, maxSoFar);

return result;

PW Skills

You might also like