Mastering JavaScript Arrays: Interview Questions and Solutions

Arrays are one of the most essential data structures in JavaScript and play a pivotal role in solving a wide range of coding problems. In interviews, you’ll often encounter questions about manipulating arrays, using array methods, and solving algorithmic problems that require a deep understanding of how arrays work in JavaScript.

This guide will cover common array methods, manipulation techniques, and interview questions to help you master JavaScript arrays and excel in your interviews.

JavaScript Arrays: The Basics

In JavaScript, an array is a list-like object that can store multiple values. Arrays can contain any data type, including numbers, strings, objects, and even other arrays (nested arrays). Arrays are zero-indexed, meaning the first element has an index of 0.

Basic Array Operations

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

// Accessing array elements
console.log(fruits[0]); // Output: 'apple'

// Adding elements
fruits.push("orange"); // Adds 'orange' to the end of the array

// Removing elements
fruits.pop(); // Removes 'orange' from the end of the array

Common JavaScript Array Methods

JavaScript provides many built-in methods to manipulate arrays. Let’s explore some of the most commonly used methods and how they are applied in interviews.

1. push() and pop()

  • push(): Adds one or more elements to the end of an array and returns the new length.
  • pop(): Removes the last element from an array and returns that element.

Example:

const numbers = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4]
numbers.pop(); // [1, 2, 3]

2. shift() and unshift()

  • shift(): Removes the first element from an array and returns it.
  • unshift(): Adds one or more elements to the beginning of an array and returns the new length.

Example:

const animals = ["dog", "cat", "rabbit"];
animals.shift(); // Removes 'dog', array becomes ['cat', 'rabbit']
animals.unshift("elephant"); // Adds 'elephant' at the start

3. splice()

  • splice(start, deleteCount, item1, item2, ...): Adds/removes elements from an array.
    • start: The index at which to start changing the array.
    • deleteCount: The number of elements to remove.
    • item1, item2, ...: Elements to add at the starting index.

Example:

const colors = ["red", "green", "blue"];
colors.splice(1, 1, "yellow"); // Removes 'green' at index 1 and adds 'yellow'
console.log(colors); // ['red', 'yellow', 'blue']

4. slice()

  • slice(start, end): Returns a shallow copy of a portion of the array without modifying the original array.

Example:

const letters = ["a", "b", "c", "d", "e"];
const sliced = letters.slice(1, 3); // Returns ['b', 'c']

5. map()

  • map(callback): Creates a new array with the results of calling a function on every element in the calling array.

Example:

const nums = [1, 2, 3];
const doubled = nums.map(num => num * 2); // [2, 4, 6]

6. filter()

  • filter(callback): Creates a new array with all elements that pass the test implemented by the provided function.

Example:

const nums = [1, 2, 3, 4];
const evens = nums.filter(num => num % 2 === 0); // [2, 4]

7. reduce()

  • reduce(callback, initialValue): Reduces the array to a single value by executing a reducer function on each element.

Example:

const nums = [1, 2, 3, 4];
const sum = nums.reduce((accumulator, current) => accumulator + current, 0); // 10

Array Manipulation Techniques

JavaScript array manipulation is a frequent topic in interviews. These techniques test your understanding of array methods and your ability to transform arrays to solve problems.

1. Reversing an Array

Interviewers may ask you to reverse an array in place or return a new array that is reversed.

const arr = [1, 2, 3, 4];
const reversed = arr.reverse();
console.log(reversed); // [4, 3, 2, 1]

Or manually:

function reverseArray(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr;
}

2. Sorting an Array

Sorting is another common interview problem. JavaScript provides the sort() method, but it can behave unexpectedly with numbers because it converts elements to strings by default.

const numbers = [10, 5, 20, 8];
numbers.sort((a, b) => a - b); // Sorts numbers in ascending order
console.log(numbers); // [5, 8, 10, 20]

3. Finding Duplicates in an Array

A typical interview problem is to find duplicates in an array.

function findDuplicates(arr) {
const duplicates = [];
const seen = new Set();
for (const num of arr) {
if (seen.has(num)) {
duplicates.push(num);
} else {
seen.add(num);
}
}
return duplicates;
}

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

4. Removing Duplicates from an Array

You may also be asked to remove duplicates from an array. The Set object provides a simple solution.

const uniqueArray = [...new Set([1, 2, 2, 3, 4, 4])];
console.log(uniqueArray); // [1, 2, 3, 4]

5. Flattening a Nested Array

Another common question involves flattening a nested array into a single-level array.

const nested = [1, [2, 3], [4, [5, 6]]];
const flatArray = nested.flat(Infinity);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]

Or using recursion:

function flattenArray(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}

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

Common JavaScript Array Interview Questions

Now that you’ve mastered the essential array methods and manipulations, let’s look at some common interview questions that test your understanding of JavaScript arrays.

1. Find the Largest Sum of Contiguous Subarray (Kadane’s Algorithm)

Question: Given an array of integers, find the maximum sum of a contiguous subarray.

function maxSubArray(nums) {
let maxSum = nums[0];
let currentSum = nums[0];

for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}

return maxSum;
}

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // Output: 6 (subarray [4, -1, 2, 1])

2. Find the Intersection of Two Arrays

Question: Given two arrays, return their intersection (common elements).

function intersection(arr1, arr2) {
const set1 = new Set(arr1);
return arr2.filter(num => set1.has(num));
}

console.log(intersection([1, 2, 3], [2, 3, 4])); // Output: [2, 3]

3. Rotate an Array

Question: Given an array, rotate it to the right by k steps, where k is non-negative.

function rotateArray(arr, k) {
k = k % arr.length;
return arr.slice(-k).concat(arr.slice(0, -k));
}

console.log(rotateArray([1, 2, 3, 4, 5], 2)); // Output: [4, 5, 1, 2, 3]

4. Check if an Array is a Subset of Another Array

Question: Write a function to check if all elements of an array are present in another array.

function isSubset(arr1, arr2) {
const set = new Set(arr2);
return arr1.every(num => set.has(num));
}

console.log(isSubset([1, 2], [1, 2, 3])); // Output: true
console.log(isSubset([1, 4], [1, 2, 3])); // Output: false

5. Find the Missing Number in an Array

Question: Given an array of n integers where the integers are in the range 0 to n, find the one number that is missing from the array.

function findMissingNumber(arr) {
const n = arr.length;
const totalSum = (n * (n + 1)) / 2;
const arraySum = arr.reduce((sum, num) => sum + num, 0);
return totalSum - arraySum;
}

console.log(findMissingNumber([0, 1, 3])); // Output: 2

Conclusion

Arrays are one of the most commonly used data structures in JavaScript, and understanding their methods and manipulation techniques is crucial for solving coding challenges. By mastering the array methods and practicing common interview problems, you’ll be well-equipped to handle any array-related question in a JavaScript interview.

Practice the problems outlined here, and explore the built-in array methods in depth to ensure that you can use them effectively in a variety of scenarios.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *