JavaScript Array Programming Interview Questions
Arrays are a fundamental data structure in JavaScript, widely used in web development. During interviews, questions about arrays test your understanding of array manipulation, iteration, and transformation. This article covers common JavaScript array programming questions, complete with code examples and explanations.
01. How do you find the largest and smallest numbers in an array?
This question tests your ability to use basic loops or JavaScript methods to work with arrays.
// Code Example:
let numbers = [10, 20, 5, 7, 99, 1];
// Using Math methods:
let largest = Math.max(...numbers);
let smallest = Math.min(...numbers);
console.log("Largest:", largest); // Output: Largest: 99
console.log("Smallest:", smallest); // Output: Smallest: 1
Explanation: The Math.max() and Math.min() functions are applied using the spread operator to expand the array.
02. How do you reverse an array without using reverse()?
Reversing an array manually showcases your understanding of array manipulation.
// Code Example:
function reverseArray(arr) {
let reversed = [];
for (let i = arr.length - 1; i >= 0; i--) {
reversed.push(arr[i]);
}
return reversed;
}
let arr = [1, 2, 3, 4, 5];
console.log(reverseArray(arr)); // Output: [5, 4, 3, 2, 1]
Explanation: Iterate through the array from the last element to the first, appending each element to a new array.
03. How do you remove duplicates from an array?
This question tests your ability to use JavaScript's Set object or other techniques to handle unique values.
// Code Example:
let numbers = [1, 2, 3, 2, 4, 1, 5];
// Using Set:
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
Explanation: A Set automatically stores unique values, and the spread operator converts it back into an array.
04. How do you check if an array contains a specific value?
Checking the existence of a value is a common task, often asked in coding interviews.
// Code Example:
let fruits = ['apple', 'banana', 'cherry'];
// Using includes:
let hasBanana = fruits.includes('banana');
console.log(hasBanana); // Output: true
// Using indexOf:
let hasGrape = fruits.indexOf('grape') !== -1;
console.log(hasGrape); // Output: false
Explanation: The includes() method checks for a value's existence, while indexOf() returns the index or -1 if not found.
05. How do you flatten a multi-dimensional array?
This question evaluates your knowledge of array transformation.
// Code Example:
let nestedArray = [1, [2, 3], [4, [5]]];
// Using flat():
let flatArray = nestedArray.flat(Infinity);
console.log(flatArray); // Output: [1, 2, 3, 4, 5]
// Using recursion:
function flattenArray(arr) {
return arr.reduce((flat, item) =>
flat.concat(Array.isArray(item) ? flattenArray(item) : item), []);
}
console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5]
Explanation: The flat() method simplifies flattening, while recursion offers a manual approach.
06. How do you find the intersection of two arrays?
This task involves finding common elements between two arrays.
// Code Example:
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [4, 5, 6, 7, 8];
let intersection = arr1.filter(value => arr2.includes(value));
console.log(intersection); // Output: [4, 5]
Explanation: The filter() method selects elements from the first array that are present in the second array.
07. How do you find the sum of all elements in an array?
Summing up array elements demonstrates your familiarity with reduce().
// Code Example:
let numbers = [1, 2, 3, 4, 5];
// Using reduce():
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 15
Explanation: The reduce() method iteratively adds elements, starting from 0.
08. How do you sort an array of numbers?
Sorting is a common requirement in array-related problems.
// Code Example:
let numbers = [10, 5, 3, 20, 1];
// Ascending order:
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 3, 5, 10, 20]
// Descending order:
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [20, 10, 5, 3, 1]
Explanation: The sort() method uses a comparator function to order elements.
09. How do you merge two arrays without duplicates?
Merging arrays and removing duplicates is a common interview task.
// Code Example:
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
// Using Set:
let mergedArray = [...new Set([...array1, ...array2])];
console.log(mergedArray); // Output: [1, 2, 3, 4]
Explanation: The spread operator combines both arrays, and Set removes duplicates.
10. How do you find the difference between two arrays?
This question tests your ability to identify unique elements in arrays.
// Code Example:
let array1 = [1, 2, 3, 4];
let array2 = [3, 4, 5, 6];
let difference = array1.filter(num => !array2.includes(num));
console.log(difference); // Output: [1, 2]
Explanation: The filter() method excludes elements from array1 that exist in array2.
11. How do you split an array into chunks of a given size?
This is useful for batching tasks or paginating data.
// Code Example:
function chunkArray(array, size) {
let result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
let array = [1, 2, 3, 4, 5];
console.log(chunkArray(array, 2)); // Output: [[1, 2], [3, 4], [5]]
Explanation: Use a loop to slice the array into smaller chunks of the specified size.
12. How do you find the first repeating element in an array?
This task assesses your knowledge of array traversal and sets.
// Code Example:
function findFirstRepeating(arr) {
let seen = new Set();
for (let num of arr) {
if (seen.has(num)) return num;
seen.add(num);
}
return null;
}
let array = [1, 2, 3, 4, 2, 5];
console.log(findFirstRepeating(array)); // Output: 2
Explanation: Use a Set to track seen elements, returning the first duplicate encountered.
13. How do you rotate an array by k positions?
This problem evaluates your ability to rearrange array elements.
// Code Example:
function rotateArray(arr, k) {
k = k % arr.length; // Handle rotations greater than array length
return arr.slice(-k).concat(arr.slice(0, -k));
}
let array = [1, 2, 3, 4, 5];
console.log(rotateArray(array, 2)); // Output: [4, 5, 1, 2, 3]
Explanation: Use slicing and concatenation to rotate the array.
14. How do you count the frequency of elements in an array?
This task tests your knowledge of using objects to store counts.
// Code Example:
function countFrequency(arr) {
let frequency = {};
for (let num of arr) {
frequency[num] = (frequency[num] || 0) + 1;
}
return frequency;
}
let array = [1, 2, 2, 3, 3, 3];
console.log(countFrequency(array)); // Output: {1: 1, 2: 2, 3: 3}
Explanation: Use an object to store and update counts for each element.
15. How do you find all pairs with a given sum in an array?
Finding pairs that satisfy a condition is a common problem.
// Code Example:
function findPairs(arr, sum) {
let pairs = [];
let seen = new Set();
for (let num of arr) {
let complement = sum - num;
if (seen.has(complement)) {
pairs.push([complement, num]);
}
seen.add(num);
}
return pairs;
}
let array = [1, 2, 3, 4, 5];
console.log(findPairs(array, 6)); // Output: [[2, 4], [1, 5]]
Explanation: Use a Set to track complements needed for the target sum.
16. How do you remove a specific element from an array?
This task is fundamental for array manipulation.
// Code Example:
let array = [1, 2, 3, 4, 5];
// Remove the number 3:
let filteredArray = array.filter(num => num !== 3);
console.log(filteredArray); // Output: [1, 2, 4, 5]
Explanation: Use filter() to exclude the unwanted element.
17. How do you find the longest word in an array of strings?
This question assesses your string and array manipulation skills.
// Code Example:
let words = ['apple', 'banana', 'cherry'];
let longestWord = words.reduce((longest, word) =>
word.length > longest.length ? word : longest, '');
console.log(longestWord); // Output: "banana"
Explanation: Use reduce() to compare and track the longest word.
18. How do you sort an array of objects by a property?
This question tests your ability to work with complex arrays.
// Code Example:
let people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 20 },
{ name: 'Charlie', age: 30 }
];
people.sort((a, b) => a.age - b.age);
console.log(people);
// Output: [{name: "Bob", age: 20}, {name: "Alice", age: 25}, {name: "Charlie", age: 30}]
Explanation: Use sort() with a comparator function to order objects by a property.
19. How do you find the second largest number in an array?
This task evaluates your ability to handle ranking and sorting.
// Code Example:
let numbers = [10, 5, 8, 20, 15];
let uniqueNumbers = [...new Set(numbers)].sort((a, b) => b - a);
let secondLargest = uniqueNumbers[1];
console.log(secondLargest); // Output: 15
Explanation: Remove duplicates, sort the array in descending order, and return the second element.
20. How do you find all permutations of an array?
This is an advanced question that tests your recursion skills.
// Code Example:
function permute(arr) {
if (arr.length === 0) return [[]];
let result = [];
for (let i = 0; i < arr.length; i++) {
let rest = arr.slice(0, i).concat(arr.slice(i + 1));
for (let perm of permute(rest)) {
result.push([arr[i], ...perm]);
}
}
return result;
}
console.log(permute([1, 2, 3]));
// Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
Explanation: Use recursion to generate all possible arrangements of the array.
Conclusion
JavaScript arrays offer a wealth of functionality, making them a critical topic for interviews. By mastering these questions and techniques, you'll be well-prepared to tackle array-related challenges in JavaScript programming interviews.
Comments
Post a Comment