JavaScript Array Coding Questions with Test Cases
Beginner Level Questions (1-10)
1. Sum of Array Elements
Write a function that calculates the sum of all elements in an array.
javascript
function sumArray(arr) {
// Your code here
}
// Test cases
console.log(sumArray([1, 2, 3, 4, 5])); // Expected output: 15
console.log(sumArray([-1, 1, 2, 3])); // Expected output: 5
console.log(sumArray([])); // Expected output: 0
2. Find Maximum Value
Write a function that finds the maximum value in an array.
javascript
function findMax(arr) {
// Your code here
}
// Test cases
console.log(findMax([1, 3, 5, 7, 9])); // Expected output: 9
console.log(findMax([-5, -2, -10, -1])); // Expected output: -1
console.log(findMax([100])); // Expected output: 100
3. Count Occurrences
Write a function that counts the occurrences of a specific element in an array.
javascript
function countOccurrences(arr, element) {
// Your code here
}
// Test cases
console.log(countOccurrences([1, 2, 3, 2, 4, 2, 5], 2)); // Expected output: 3
console.log(countOccurrences(['apple', 'banana', 'apple', 'orange'], 'apple')); // Expe
console.log(countOccurrences([1, 2, 3], 4)); // Expected output: 0
4. Reverse Array
Write a function that reverses an array without using the built-in reverse() method.
javascript
function reverseArray(arr) {
// Your code here
}
// Test cases
console.log(reverseArray([1, 2, 3, 4, 5])); // Expected output: [5, 4, 3, 2, 1]
console.log(reverseArray(['a', 'b', 'c'])); // Expected output: ['c', 'b', 'a']
console.log(reverseArray([])); // Expected output: []
5. Even Numbers Filter
Write a function that filters out all the even numbers from an array.
javascript
function filterEvenNumbers(arr) {
// Your code here
}
// Test cases
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6])); // Expected output: [2, 4, 6]
console.log(filterEvenNumbers([11, 13, 15])); // Expected output: []
console.log(filterEvenNumbers([2, 4, 6, 8])); // Expected output: [2, 4, 6, 8]
6. Array Average
Write a function that calculates the average of elements in an array.
javascript
function calculateAverage(arr) {
// Your code here
}
// Test cases
console.log(calculateAverage([1, 2, 3, 4, 5])); // Expected output: 3
console.log(calculateAverage([10, 20, 30, 40])); // Expected output: 25
console.log(calculateAverage([])); // Expected output: 0 (or null, depending on how you
7. Merge Arrays
Write a function that merges two arrays into a single array.
javascript
function mergeArrays(arr1, arr2) {
// Your code here
}
// Test cases
console.log(mergeArrays([1, 2, 3], [4, 5, 6])); // Expected output: [1, 2, 3, 4, 5, 6]
console.log(mergeArrays(['a', 'b'], ['c', 'd'])); // Expected output: ['a', 'b', 'c',
console.log(mergeArrays([], [1, 2, 3])); // Expected output: [1, 2, 3]
8. Remove Duplicates
Write a function that removes duplicate elements from an array.
javascript
function removeDuplicates(arr) {
// Your code here
}
// Test cases
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Expected output: [1, 2, 3, 4,
console.log(removeDuplicates(['a', 'b', 'a', 'c', 'c'])); // Expected output: ['a', 'b
console.log(removeDuplicates([1, 1, 1, 1])); // Expected output: [1]
9. Array Contains
Write a function that checks if an array contains a specific value.
javascript
function arrayContains(arr, value) {
// Your code here
}
// Test cases
console.log(arrayContains([1, 2, 3, 4, 5], 3)); // Expected output: true
console.log(arrayContains(['apple', 'banana', 'orange'], 'grape')); // Expected output
console.log(arrayContains([], 1)); // Expected output: false
10. Find Index
Write a function that finds the index of a specific element in an array. Return -1 if the element is not
found.
javascript
function findIndex(arr, element) {
// Your code here
}
// Test cases
console.log(findIndex([10, 20, 30, 40, 50], 30)); // Expected output: 2
console.log(findIndex(['apple', 'banana', 'orange'], 'banana')); // Expected output: 1
console.log(findIndex([1, 2, 3], 4)); // Expected output: -1
Intermediate Level Questions (11-25)
11. Map Function Implementation
Write your own version of the map function without using the built-in map() method.
javascript
function customMap(arr, callback) {
// Your code here
}
// Test cases
console.log(customMap([1, 2, 3], num => num * 2)); // Expected output: [2, 4, 6]
console.log(customMap(['hello', 'world'], str => str.toUpperCase())); // Expected outpu
console.log(customMap([10, 20, 30], num => num / 10)); // Expected output: [1, 2, 3]
12. Filter Function Implementation
Write your own version of the filter function without using the built-in filter() method.
javascript
function customFilter(arr, callback) {
// Your code here
}
// Test cases
console.log(customFilter([1, 2, 3, 4, 5], num => num % 2 === 0)); // Expected output:
console.log(customFilter(['apple', 'banana', 'kiwi', 'orange'], word => word.length > 5
console.log(customFilter([10, 20, 30], num => num > 50)); // Expected output: []
13. Reduce Function Implementation
Write your own version of the reduce function without using the built-in reduce() method.
javascript
function customReduce(arr, callback, initialValue) {
// Your code here
}
// Test cases
console.log(customReduce([1, 2, 3, 4], (acc, curr) => acc + curr, 0)); // Expected outp
console.log(customReduce([1, 2, 3], (acc, curr) => acc * curr, 1)); // Expected output
console.log(customReduce(['a', 'b', 'c'], (acc, curr) => acc + curr, '')); // Expected
14. Sort Array of Objects
Write a function that sorts an array of objects by a specific property.
javascript
function sortByProperty(arr, prop) {
// Your code here
}
// Test cases
const people = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
];
console.log(sortByProperty(people, 'age'));
// Expected output: [{ name: 'Alice', age: 25 }, { name: 'John', age: 30 }, { name: 'Bo
const fruits = [
{ name: 'banana', color: 'yellow' },
{ name: 'apple', color: 'red' },
{ name: 'grape', color: 'purple' }
];
console.log(sortByProperty(fruits, 'name'));
// Expected output: [{ name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow
15. Group By
Write a function that groups array elements by a key returned by the callback function.
javascript
function groupBy(arr, callback) {
// Your code here
}
// Test cases
console.log(groupBy([6.1, 4.2, 6.3], Math.floor));
// Expected output: { '4': [4.2], '6': [6.1, 6.3] }
console.log(groupBy(['one', 'two', 'three'], str => str.length));
// Expected output: { '3': ['one', 'two'], '5': ['three'] }
console.log(groupBy([{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Cha
// Expected output: { '25': [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
16. Chunk Array
Write a function that splits an array into chunks of a specific size.
javascript
function chunkArray(arr, size) {
// Your code here
}
// Test cases
console.log(chunkArray([1, 2, 3, 4, 5], 2)); // Expected output: [[1, 2], [3, 4], [5]]
console.log(chunkArray([1, 2, 3, 4, 5, 6, 7, 8], 3)); // Expected output: [[1, 2, 3],
console.log(chunkArray([1, 2, 3], 5)); // Expected output: [[1, 2, 3]]
17. Flatten Array (One Level)
Write a function that flattens a nested array by one level.
javascript
function flattenArray(arr) {
// Your code here
}
// Test cases
console.log(flattenArray([1, [2, 3], 4, [5, 6]])); // Expected output: [1, 2, 3, 4, 5,
console.log(flattenArray([['a', 'b'], ['c', 'd'], 'e'])); // Expected output: ['a', 'b
console.log(flattenArray([[1, 2], [3, [4, 5]], 6])); // Expected output: [1, 2, 3, [4,
18. Intersection of Arrays
Write a function that returns the intersection of two arrays (elements that exist in both arrays).
javascript
function findIntersection(arr1, arr2) {
// Your code here
}
// Test cases
console.log(findIntersection([1, 2, 3, 4], [3, 4, 5, 6])); // Expected output: [3, 4]
console.log(findIntersection(['a', 'b', 'c'], ['b', 'c', 'd'])); // Expected output: [
console.log(findIntersection([1, 2, 3], [4, 5, 6])); // Expected output: []
19. Difference of Arrays
Write a function that returns the difference between two arrays (elements that exist in the first array
but not in the second).
javascript
function findDifference(arr1, arr2) {
// Your code here
}
// Test cases
console.log(findDifference([1, 2, 3, 4], [3, 4, 5, 6])); // Expected output: [1, 2]
console.log(findDifference(['a', 'b', 'c'], ['b', 'c', 'd'])); // Expected output: ['a
console.log(findDifference([1, 2, 3], [1, 2, 3])); // Expected output: []
20. Find Duplicates
Write a function that finds all duplicates in an array.
javascript
function findDuplicates(arr) {
// Your code here
}
// Test cases
console.log(findDuplicates([1, 2, 2, 3, 4, 4, 5])); // Expected output: [2, 4]
console.log(findDuplicates(['a', 'b', 'a', 'c', 'c'])); // Expected output: ['a', 'c']
console.log(findDuplicates([1, 2, 3, 4])); // Expected output: []
21. Rotate Array
Write a function that rotates the elements of an array to the right by a given number of steps.
javascript
function rotateArray(arr, steps) {
// Your code here
}
// Test cases
console.log(rotateArray([1, 2, 3, 4, 5], 2)); // Expected output: [4, 5, 1, 2, 3]
console.log(rotateArray([1, 2, 3], 1)); // Expected output: [3, 1, 2]
console.log(rotateArray([1, 2, 3, 4, 5], 5)); // Expected output: [1, 2, 3, 4, 5]
22. Zip Arrays
Write a function that combines multiple arrays by taking one element from each array in turn.
javascript
function zipArrays(...arrays) {
// Your code here
}
// Test cases
console.log(zipArrays([1, 2, 3], ['a', 'b', 'c'])); // Expected output: [[1, 'a'], [2,
console.log(zipArrays([1, 2], ['a', 'b'], [true, false])); // Expected output: [[1, 'a
console.log(zipArrays([1, 2, 3], ['a', 'b'])); // Expected output: [[1, 'a'], [2, 'b'],
23. Remove Elements by Indices
Write a function that removes elements from an array at specified indices.
javascript
function removeAtIndices(arr, indices) {
// Your code here
}
// Test cases
console.log(removeAtIndices([1, 2, 3, 4, 5], [1, 3])); // Expected output: [1, 3, 5]
console.log(removeAtIndices(['a', 'b', 'c', 'd'], [0, 3])); // Expected output: ['b',
console.log(removeAtIndices([1, 2, 3], [])); // Expected output: [1, 2, 3]
24. Frequency Counter
Write a function that counts the frequency of each element in an array and returns an object with
elements as keys and their frequencies as values.
javascript
function frequencyCounter(arr) {
// Your code here
}
// Test cases
console.log(frequencyCounter([1, 2, 2, 3, 3, 3, 4])); // Expected output: { '1': 1, '2
console.log(frequencyCounter(['a', 'b', 'a', 'c', 'a'])); // Expected output: { 'a': 3,
console.log(frequencyCounter([])); // Expected output: {}
25. Find Missing Number
Write a function that finds the missing number in an array containing numbers from 1 to n with one
number missing.
javascript
function findMissingNumber(arr, n) {
// Your code here
}
// Test cases
console.log(findMissingNumber([1, 2, 4, 5], 5)); // Expected output: 3
console.log(findMissingNumber([1, 3, 4, 5, 6], 6)); // Expected output: 2
console.log(findMissingNumber([2, 3, 4, 5, 6], 6)); // Expected output: 1
Advanced Level Questions (26-30)
26. Deep Flatten Array
Write a function that flattens a deeply nested array of any depth.
javascript
function deepFlatten(arr) {
// Your code here
}
// Test cases
console.log(deepFlatten([1, [2, [3, [4]], 5]])); // Expected output: [1, 2, 3, 4, 5]
console.log(deepFlatten([[1, 2], [3, 4], [5, [6, [7]]]])); // Expected output: [1, 2, 3
console.log(deepFlatten([1, 2, 3])); // Expected output: [1, 2, 3]
27. Cartesian Product
Write a function that returns the Cartesian product of two arrays.
javascript
function cartesianProduct(arr1, arr2) {
// Your code here
}
// Test cases
console.log(cartesianProduct([1, 2], ['a', 'b'])); // Expected output: [[1, 'a'], [1,
console.log(cartesianProduct([1, 2, 3], ['x', 'y'])); // Expected output: [[1, 'x'], [1
console.log(cartesianProduct([], [1, 2])); // Expected output: []
28. Array Permutations
Write a function that generates all possible permutations of an array.
javascript
function findPermutations(arr) {
// Your code here
}
// Test cases
console.log(findPermutations([1, 2])); // Expected output: [[1, 2], [2, 1]]
console.log(findPermutations([1, 2, 3])); // Expected output: [[1, 2, 3], [1, 3, 2], [2
console.log(findPermutations([1])); // Expected output: [[1]]
29. Custom Iterator
Write a function that creates a custom iterator for an array that can be used with a for...of loop and
implements methods like next() , map() , and filter() .
javascript
function createArrayIterator(arr) {
// Your code here
}
// Test cases
const iterator1 = createArrayIterator([1, 2, 3]);
console.log(iterator1.next()); // Expected output: { value: 1, done: false }
console.log(iterator1.next()); // Expected output: { value: 2, done: false }
console.log(iterator1.next()); // Expected output: { value: 3, done: false }
console.log(iterator1.next()); // Expected output: { value: undefined, done: true }
const iterator2 = createArrayIterator([1, 2, 3, 4]);
const mappedIterator = iterator2.map(x => x * 2);
console.log([...mappedIterator]); // Expected output: [2, 4, 6, 8]
const iterator3 = createArrayIterator([1, 2, 3, 4, 5]);
const filteredIterator = iterator3.filter(x => x % 2 === 0);
console.log([...filteredIterator]); // Expected output: [2, 4]
30. Memoized Array Operations
Write a function that implements a memoized version of common array operations (like find, filter,
map) to optimize performance for repeated operations.
javascript
function createMemoizedArray(arr) {
// Your code here
}
// Test cases
const arr = [1, 2, 3, 4, 5];
const memoizedArr = createMemoizedArray(arr);
// Should execute the callback the first time
console.time('First find');
const result1 = memoizedArr.find(x => x > 3);
console.timeEnd('First find');
console.log(result1); // Expected output: 4
// Should return cached result without executing callback
console.time('Second find');
const result2 = memoizedArr.find(x => x > 3);
console.timeEnd('Second find');
console.log(result2); // Expected output: 4 (should be faster)
// Filter test
console.time('First filter');
const filterResult1 = memoizedArr.filter(x => x % 2 === 0);
console.timeEnd('First filter');
console.log(filterResult1); // Expected output: [2, 4]
console.time('Second filter');
const filterResult2 = memoizedArr.filter(x => x % 2 === 0);
console.timeEnd('Second filter');
console.log(filterResult2); // Expected output: [2, 4] (should be faster)