15 JavaScript Array Interview Questions and Answers
Prepare for your next interview with this guide on JavaScript arrays, featuring common questions and detailed answers to enhance your skills.
Prepare for your next interview with this guide on JavaScript arrays, featuring common questions and detailed answers to enhance your skills.
JavaScript arrays are a fundamental aspect of web development, playing a crucial role in handling and manipulating data. Arrays in JavaScript are versatile, allowing developers to store multiple values in a single variable and perform a variety of operations such as sorting, filtering, and iterating. Mastery of JavaScript arrays is essential for creating dynamic and efficient web applications, making it a key skill for any developer.
This article provides a curated selection of interview questions focused on JavaScript arrays. By working through these questions and their detailed answers, you will gain a deeper understanding of array manipulation techniques and be better prepared to demonstrate your proficiency in technical interviews.
map
method to transform an array of numbers by doubling each value?The map
method in JavaScript is used to create a new array by applying a function to each element of an existing array. It returns a new array with the transformed values.
Example:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
filter
method to create a new array with all elements that pass a test implemented by a provided function.The filter
method creates a new array with elements that pass a test implemented by a provided function. The function is called for each element, and only those for which the function returns true
are included in the new array.
Example:
const numbers = [1, 2, 3, 4, 5, 6]; const isEven = (num) => num % 2 === 0; const evenNumbers = numbers.filter(isEven); console.log(evenNumbers); // Output: [2, 4, 6]
Flattening a nested array involves converting it into a single, one-dimensional array. This can be achieved using the Array.prototype.flat()
method, which concatenates sub-array elements into it recursively up to the specified depth.
Example:
const nestedArray = [1, [2, [3, [4]], 5]]; const flattenedArray = nestedArray.flat(Infinity); console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]
arguments
, into a true array?Array-like objects have a length
property and indexed elements but lack array methods. To convert them into true arrays, you can use Array.prototype.slice.call
, Array.from
, or the spread operator.
Example:
function example() { var args = Array.from(arguments); console.log(args); // Now 'args' is a true array } example(1, 2, 3);
When working with large arrays, consider memory usage, time complexity, and minimizing operations. Use built-in methods, and consider alternative data structures if needed.
Example:
const largeArray = new Array(1000000).fill(1); const sum = largeArray.reduce((acc, val) => acc + val, 0); console.log(sum); // 1000000
ArrayBuffer is a fixed-length binary data buffer. Typed Arrays are views on top of an ArrayBuffer that allow you to read and write the binary data in a specific format.
Example:
let buffer = new ArrayBuffer(16); let int32View = new Int32Array(buffer); int32View[0] = 42; int32View[1] = 84; console.log(int32View[0]); // 42 console.log(int32View[1]); // 84
To find the median of an array of numbers, sort the array and find the middle element(s). Extend the Array prototype to add a custom method.
Array.prototype.median = function() { if (this.length === 0) return null; const sorted = this.slice().sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { return (sorted[mid - 1] + sorted[mid]) / 2; } else { return sorted[mid]; } }; const numbers = [3, 5, 1, 4, 2]; console.log(numbers.median()); // Output: 3
To optimize array operations, minimize traversals, use efficient methods, and avoid mutating arrays. Consider using Typed Arrays for performance-critical applications.
Example:
let arr = [1, 2, 3, 4, 5]; let sum = 0; let product = 1; for (let i = 0; i < arr.length; i++) { sum += arr[i]; product *= arr[i]; }
Quicksort is a divide-and-conquer algorithm that sorts an array by selecting a ‘pivot’ and partitioning other elements into sub-arrays, which are then sorted recursively.
Example:
function quicksort(arr) { if (arr.length <= 1) { return arr; } const pivot = arr[Math.floor(arr.length / 2)]; const left = arr.filter(x => x < pivot); const right = arr.filter(x => x > pivot); return [...quicksort(left), pivot, ...quicksort(right)]; } const numbers = [3, 6, 8, 10, 1, 2, 1]; console.log(quicksort(numbers)); // [1, 1, 2, 3, 6, 8, 10]
To process large datasets without memory issues, use techniques like pagination, lazy loading, or generators to handle data in smaller chunks.
Example using a generator:
function* dataGenerator(dataArray) { for (let item of dataArray) { yield item; } } const largeArray = new Array(1000000).fill().map((_, i) => i); const generator = dataGenerator(largeArray); for (let i = 0; i < 100; i++) { console.log(generator.next().value); }
Arrays can be used in a functional programming style with methods like map
, filter
, and reduce
, which allow operations without mutating the original array.
Example:
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); const evens = numbers.filter(num => num % 2 === 0); const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(doubled); // [2, 4, 6, 8, 10] console.log(evens); // [2, 4] console.log(sum); // 15
A stack is a Last In, First Out (LIFO) data structure. Arrays can implement a stack using methods like push and pop.
Example:
class Stack { constructor() { this.items = []; } push(element) { this.items.push(element); } pop() { if (this.isEmpty()) { return "Stack is empty"; } return this.items.pop(); } peek() { if (this.isEmpty()) { return "Stack is empty"; } return this.items[this.items.length - 1]; } isEmpty() { return this.items.length === 0; } size() { return this.items.length; } }
map
, filter
, and reduce
.The map
, filter
, and reduce
methods manipulate and transform arrays in different ways.
– map
creates a new array by applying a function to each element.
– filter
creates a new array with elements that pass a test.
– reduce
applies a function to reduce an array to a single value.
Example:
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); const even = numbers.filter(num => num % 2 === 0); const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(doubled); // [2, 4, 6, 8] console.log(even); // [2, 4] console.log(sum); // 10
The time complexities of common array operations are:
– Push: O(1)
– Pop: O(1)
– Shift: O(n)
– Unshift: O(n)
– Accessing an element by index: O(1)
JavaScript uses automatic garbage collection to manage memory. The garbage collector identifies and frees memory that is no longer in use. To avoid memory leaks, be cautious with global variables, closures, event listeners, and detached DOM elements.