Mid-Level JavaScript Interview Questions-Solutions (About Arrays)
I’ve shown 9 questions related to arrays in JavaScript that I’ve encountered in mid-level interviews and beyond, along with their answers. I hope this article proves to be helpful to you as you navigate through these common array-related challenges in your JavaScript interviews.
1- Print unique values from an array
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
2- How do you use the reduce()
method to sum elements in an array without using a loop?
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, current) => acc + current, 0);
console.log(sum); // 15
3- How can you flatten a nested array into a single flat array?
const arr = [1, [2, 3], [4, [5, 6]]];
const flatArr = arr.flat(Infinity);
console.log(flatArr); // [1, 2, 3, 4, 5, 6]
4- How can you find the intersection of two arrays?
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
const intersection = arr1.filter(item => arr2.includes(item));
console.log(intersection); // [3, 4]
5- Write a function that swaps the first two elements in a given array (solve with destructing)
function swapFirstTwo([first, second, ...rest]) {
return [second, first, ...rest];
}
const array = [3, 5, 1, 4, 2];
console.log(swapFirstTwo(array)); // [5, 3, 1, 4, 2]
6- Explain different ways to reverse an array and show each with a code example
// Reversing Array Elements Method 1: Using the reverse() method
const arr1 = [1, 2, 3, 4, 5];
const reversedArr1 = arr1.reverse();
console.log(reversedArr1); // [5, 4, 3, 2, 1]
// Reversing Array Elements Method 2: Using the spread operator and reverse()
const arr2 = [1, 2, 3, 4, 5];
const reversedArr2 = [...arr2].reverse();
console.log(reversedArr2); // [5, 4, 3, 2, 1]
7- Explain different ways to sort an array in descending order and show each with a code example.
Method 1: Using sort()
with a Compare Function
The sort()
method can take a compare function that defines the sort order.
const arr = [3, 1, 4, 2, 5];
arr.sort((a, b) => b - a);
console.log(arr); // Output: [5, 4, 3, 2, 1]
- The compare function
(a, b) => b - a
sorts the array in descending numerical order. - This method sorts the array in place, modifying the original array.
Method 2: Using Spread Operator and sort()
To avoid mutating the original array, you can create a copy using the spread operator and then sort it.
const arr = [3, 1, 4, 2, 5];
const sortedArr = [...arr].sort((a, b) => b - a);
console.log(sortedArr); // Output: [5, 4, 3, 2, 1]
console.log(arr); // Original array remains unchanged
[...arr]
creates a shallow copy of the original array.- Sorting the copied array does not affect the original array.
Method 3: Using slice()
and sort()
Another way to copy the array before sorting is using the slice()
method.
const arr = [3, 1, 4, 2, 5];
const sortedArr = arr.slice().sort((a, b) => b - a);
console.log(sortedArr); // Output: [5, 4, 3, 2, 1]
console.log(arr); // Original array remains unchanged
arr.slice()
creates a shallow copy of the array.- The copied array is then sorted without modifying the original array.
Method 4: Using Array.from()
and sort()
You can also use Array.from()
to create a copy before sorting.
const arr = [3, 1, 4, 2, 5];
const sortedArr = Array.from(arr).sort((a, b) => b - a);
console.log(sortedArr); // Output: [5, 4, 3, 2, 1]
console.log(arr); // Original array remains unchanged
8- How do you use the filter()
method to filter out odd numbers from an array?
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8]
9- (Bonus) - Can you copy an array in different ways, and which method is the safest for preventing unintended modifications to the original array?
First solution: Using the spread operator (
...
). This method creates a new array by spreading the elements of the original array.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = [...originalArray];
console.log(copiedArray); // [1, 2, 3, 4, 5]
Second Solution: Using the
Array.from()
method. This method creates a new, shallow-copied array instance from an array-like or iterable object.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = Array.from(originalArray);
console.log(copiedArray); // [1, 2, 3, 4, 5]
Third Solution: Using the
slice()
method. This method returns a shallow copy of a portion of an array into a new array object.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
console.log(copiedArray); // [1, 2, 3, 4, 5]
Safest Method
All three methods above create shallow copies of the original array. This means that for arrays containing only primitive values (like numbers, strings, booleans), these methods are sufficient to prevent unintended modifications to the original array.
However, if the array contains nested objects or arrays (reference types), changes to those nested structures in the copied array will also affect the original array. To prevent this, you need to create a deep copy of the array.
Deep Copy Methods:
1- Using structuredClone()
(Modern Browsers and Environments):
const originalArray = [1, 2, { a: 3 }, [4, 5]];
const copiedArray = structuredClone(originalArray);
copiedArray[2].a = 99;
copiedArray[3][0] = 44;
console.log(originalArray); // Output: [1, 2, { a: 3 }, [4, 5]]
console.log(copiedArray); // Output: [1, 2, { a: 99 }, [44, 5]]
Note: structuredClone()
creates a deep copy of a value, allowing for safe copying of complex data structures.
2- Using JSON.parse(JSON.stringify())
:
const originalArray = [1, 2, { a: 3 }, [4, 5]];
const copiedArray = JSON.parse(JSON.stringify(originalArray));
copiedArray[2].a = 99;
copiedArray[3][0] = 44;
console.log(originalArray); // Output: [1, 2, { a: 3 }, [4, 5]]
console.log(copiedArray); // Output: [1, 2, { a: 99 }, [44, 5]]
Note: This method does not copy functions or undefined
values and may not handle special object types like Date
or RegExp
correctly.
Conclusion:
- For arrays containing only primitive values, any of the three methods (
spread operator
,Array.from()
,slice()
) are safe to use. - For arrays containing nested objects or arrays, using
structuredClone()
is the safest method to prevent unintended modifications to the original array. - If
structuredClone()
is not available,JSON.parse(JSON.stringify())
is an alternative, though it has limitations. - Therefore,
structuredClone()
is the safest method among these for preventing unintended modifications to the original array in all cases.