JavaScript Challenges to Master Array Manipulation
Array manipulation is a crucial skill in JavaScript, and mastering it can significantly enhance your coding abilities. Here are ten challenges designed to help you practice and refine your array manipulation skills. Each challenge includes a solution and explanation. Try solving these challenges on your own before checking the provided solutions!
Challenge 1: Reverse an Array
Task: Write a function to reverse the order of elements in an array.
Example:
reverseArray([1, 2, 3, 4]); // [4, 3, 2, 1]
Solution:
function reverseArray(arr) { return arr.reverse(); }
Explanation: The .reverse()
method reverses the elements of the array in place and returns the reversed array.
Challenge 2: Remove Duplicates
Task: Write a function to remove duplicate values from an array.
Example:
removeDuplicates([1, 2, 2, 3, 4, 4]); // [1, 2, 3, 4]
Solution:
function removeDuplicates(arr) { return [...new Set(arr)]; }
Explanation: The Set
object lets you store unique values. By converting the array to a Set
and then spreading it back into an array, you remove duplicates.
Challenge 3: Find the Largest Number
Task: Write a function to find the largest number in an array.
Example:
findLargest([1, 2, 3, 4, 5]); // 5
Solution:
function findLargest(arr) { return Math.max(...arr); }
Explanation: The Math.max()
function returns the largest of the numbers provided. The spread operator ...
expands the array elements into individual arguments.
Challenge 4: Filter Odd Numbers
Task: Write a function to filter out only the odd numbers from an array.
Example:
filterOddNumbers([1, 2, 3, 4, 5]); // [1, 3, 5]
Solution:
function filterOddNumbers(arr) { return arr.filter(num => num % 2 !== 0); }
Explanation: The .filter()
method creates a new array with all elements that pass the test implemented by the provided function. Here, num % 2 !== 0
tests if a number is odd.
Challenge 5: Find the Average
Task: Write a function to calculate the average of an array of numbers.
Example:
findAverage([1, 2, 3, 4, 5]); // 3
Solution:
function findAverage(arr) { const sum = arr.reduce((acc, num) => acc + num, 0); return sum / arr.length; }
Explanation: The .reduce()
method calculates the sum of all elements, and dividing this sum by the length of the array gives the average.
Challenge 6: Merge Two Arrays
Task: Write a function to merge two arrays into one.
Example:
mergeArrays([1, 2], [3, 4]); // [1, 2, 3, 4]
Solution:
function mergeArrays(arr1, arr2) { return [...arr1, ...arr2]; }
Explanation: The spread operator ...
is used to merge arrays into a new array.
Challenge 7: Find the Intersection of Two Arrays
Task: Write a function to find the common elements between two arrays.
Example:
findIntersection([1, 2, 3], [2, 3, 4]); // [2, 3]
Solution:
function findIntersection(arr1, arr2) { return arr1.filter(value => arr2.includes(value)); }
Explanation: The .filter()
method is used to keep only the elements that are present in both arrays.
Challenge 8: Flatten a Nested Array
Task: Write a function to flatten a nested array into a single array.
Example:
flattenArray([1, [2, [3, 4], 5]]); // [1, 2, 3, 4, 5]
Solution:
function flattenArray(arr) { return arr.flat(Infinity); }
Explanation: The .flat()
method is used to flatten the array. The Infinity
argument ensures that all nested arrays are flattened.
Challenge 9: Find the Index of an Element
Task: Write a function to find the index of the first occurrence of a specified element in an array.
Example:
findIndex([1, 2, 3, 4], 3); // 2
Solution:
function findIndex(arr, element) { return arr.indexOf(element); }
Explanation: The .indexOf()
method returns the index of the first occurrence of the specified element or -1
if it is not found.
Challenge 10: Sort an Array of Objects by a Property
Task: Write a function to sort an array of objects by a specified property.
Example:
const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 20 } ]; sortByProperty(users, 'age'); // [{ name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]
Solution:
function sortByProperty(arr, property) { return arr.sort((a, b) => a[property] - b[property]); }
Explanation: The .sort()
method sorts the elements of an array in place. By providing a comparison function, you can sort based on a specific property.
Challenge 11: Remove All Instances of a Value
Task: Write a function to remove all instances of a specified value from an array.
Example:
removeAllInstances([1, 2, 3, 2, 4], 2); // [1, 3, 4]
Solution:
function removeAllInstances(arr, value) { return arr.filter(item => item !== value); }
Explanation: The .filter()
method is used to exclude all occurrences of the specified value.
Challenge 12: Find the Second Largest Number
Task: Write a function to find the second largest number in an array.
Example:
findSecondLargest([1, 2, 3, 4, 5]); // 4
Solution:
function findSecondLargest(arr) { const uniqueArr = [...new Set(arr)]; uniqueArr.sort((a, b) => b - a); return uniqueArr[1]; }
Explanation: By removing duplicates and sorting the array in descending order, the second largest element is at index 1.
Challenge 13: Group Array Elements by Size
Task: Write a function to group array elements by size (length).
Example:
groupBySize(['a', 'ab', 'abc', 'abcd']); // { '1': ['a'], '2': ['ab'], '3': ['abc'], '4': ['abcd'] }
Solution:
function groupBySize(arr) { return arr.reduce((acc, item) => { const size = item.length; if (!acc[size]) acc[size] = []; acc[size].push(item); return acc; }, {}); }
Explanation: The .reduce()
method groups items by their length, creating an object with lengths as keys.
Challenge 14: Rotate an Array
Task: Write a function to rotate the elements of an array by a given number of positions.
Example:
rotateArray([1, 2, 3, 4, 5], 2); // [4, 5, 1, 2, 3]
Solution:
function rotateArray(arr, positions) { return [...arr.slice(positions), ...arr.slice(0, positions)]; }
Explanation: The array is split into two parts: from positions
to the end, and from the start to positions
. Then concatenated together.
Challenge 15: Check if Array is Palindrome
Task: Write a function to check if an array is a palindrome (reads the same backward as forward).
Example:
isPalindrome([1, 2, 3, 2, 1]); // true
Solution:
function isPalindrome(arr) { return arr.join('') === arr.slice().reverse().join(''); }
Explanation: Convert the array to a string and check if it is equal to its reversed version.
Challenge 16: Flatten an Array with a Depth Limit
Task: Write a function to flatten a nested array up to a specified depth.
Example:
flattenArrayDepth([1, [2, [3, 4], 5]], 1); // [1, 2, [3, 4], 5]
Solution:
function flattenArrayDepth(arr, depth) { return arr.flat(depth); }
Explanation: Use the .flat()
method with a specified depth to control how deeply nested arrays are flattened.
Challenge 17: Find the Longest String
Task: Write a function to find the longest string in an array.
Example:
findLongestString(['a', 'ab', 'abc', 'abcd']); // 'abcd'
Solution:
function findLongestString(arr) { return arr.reduce((longest, current) => current.length > longest.length ? current : longest, ''); }
Explanation: The .reduce()
method iterates through the array, comparing lengths to find the longest string.
Challenge 18: Count Occurrences of Each Element
Task: Write a function to count the occurrences of each element in an array.
Example:
countOccurrences([1, 2, 2, 3, 3, 3]); // { '1': 1, '2': 2, '3': 3 }
Solution:
function countOccurrences(arr) { return arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}); }
Explanation: The .reduce()
method builds an object where each key is an array element, and the value is the count of occurrences.
Challenge 19: Find Missing Number
Task: Write a function to find the missing number in a sequential array of integers from 1 to n.
Example:
findMissingNumber([1, 2, 4, 5]); // 3
Solution:
function findMissingNumber(arr) { const n = arr.length + 1; const totalSum = (n * (n + 1)) / 2; const arraySum = arr.reduce((acc, num) => acc + num, 0); return totalSum - arraySum; }
Explanation: Calculate the expected sum of numbers from 1 to n, subtract the sum of the array, and get the missing number.
Challenge 20: Merge Overlapping Intervals
Task: Write a function to merge overlapping intervals in an array.
Example:
mergeIntervals([[1, 3], [2, 6], [8, 10], [15, 18]]); // [[1, 6], [8, 10], [15, 18]]
Solution:
function mergeIntervals(intervals) { if (intervals.length <= 1) return intervals; intervals.sort((a, b) => a[0] - b[0]); const merged = [intervals[0]]; for (let i = 1; i < intervals.length; i++) { const last = merged[merged.length - 1]; const current = intervals[i]; if (current[0] <= last[1]) { last[1] = Math.max(last[1], current[1]); } else { merged.push(current); } } return merged; }
Explanation: Sort the intervals and merge them if they overlap.
Challenge 21: Find Unique Elements in Two Arrays
Task: Write a function to find unique elements that are present in either of the two arrays but not in both.
Example:
findUniqueElements([1, 2, 3], [3, 4, 5]); // [1, 2, 4, 5]
Solution:
function findUniqueElements(arr1, arr2) { return [...new Set([...arr1, ...arr2].filter(x => !arr1.includes(x) || !arr2.includes(x)))]; }
Explanation: Combine both arrays, filter out elements present in both arrays, and use Set
to ensure uniqueness.
Challenge 22: Find Common Elements in Multiple Arrays
Task: Write a function to find common elements in multiple arrays.
Example:
findCommonElements([[1, 2, 3], [2, 3, 4], [3, 5, 6]]); // [3]
Solution:
function findCommonElements(arrays) { return arrays.reduce((acc, arr) => acc.filter(value => arr.includes(value))); }
Explanation: Start with the first array and filter elements that are present in all other arrays.
Challenge 23: Sort Array of Objects by Multiple Properties
Task: Write a function to sort an array of objects by multiple properties.
Example:
const items = [ { name: 'apple', price: 2 }, { name: 'banana', price: 1 }, { name: 'apple', price: 1 } ]; sortByProperties(items, ['name', 'price']); // [{ name: 'apple', price: 1 }, { name: 'apple', price: 2 }, { name: 'banana', price: 1 }]
Solution:
function sortByProperties(arr, properties) { return arr.sort((a, b) => { for (const prop of properties) { if (a[prop] < b[prop]) return -1; if (a[prop] > b[prop]) return 1; } return 0; }); }
Explanation: The .sort()
method uses a comparison function that iterates over multiple properties to sort objects.
Challenge 24: Generate an Array of Sequential Numbers
Task: Write a function to generate an array of sequential numbers from a given start to end value.
Example:
generateSequentialArray(1, 5); // [ 1, 2, 3, 4, 5]
Solution:
function generateSequentialArray(start, end) { return Array.from({ length: end - start + 1 }, (_, i) => start + i); }
Explanation: The Array.from()
method creates a new array with the specified length and fills it with sequential numbers.
Challenge 25: Remove All Falsey Values
Task: Write a function to remove all falsey values from an array (e.g., false
, 0
, ''
, null
, undefined
, NaN
).
Example:
removeFalseyValues([1, 0, '', null, 'hello', undefined, NaN]); // [1, 'hello']
Solution:
function removeFalseyValues(arr) { return arr.filter(Boolean); }
Explanation: The Boolean
constructor converts each value to true
or false
. Only truthy values pass through the filter.
Challenge 26: Convert Array to Object
Task: Write a function to convert an array of key-value pairs into an object.
Example:
arrayToObject([['name', 'Alice'], ['age', 25]]); // { name: 'Alice', age: 25 }
Solution:
function arrayToObject(arr) { return Object.fromEntries(arr); }
Explanation: The Object.fromEntries()
method converts an array of key-value pairs into an object.
Challenge 27: Find Index of Last Occurrence
Task: Write a function to find the index of the last occurrence of a specified element in an array.
Example:
findLastIndex([1, 2, 3, 2, 1], 2); // 3
Solution:
function findLastIndex(arr, element) { return arr.lastIndexOf(element); }
Explanation: The .lastIndexOf()
method returns the index of the last occurrence of the specified element.
Challenge 28: Extract a Subarray
Task: Write a function to extract a subarray from an array, given start and end indices.
Example:
extractSubarray([1, 2, 3, 4, 5], 1, 3); // [2, 3, 4]
Solution:
function extractSubarray(arr, start, end) { return arr.slice(start, end); }
Explanation: The .slice()
method extracts a section of an array and returns it as a new array.
Challenge 29: Check if Array Contains All Elements
Task: Write a function to check if an array contains all elements from another array.
Example:
containsAll([1, 2, 3, 4], [2, 4]); // true
Solution:
function containsAll(arr, elements) { return elements.every(element => arr.includes(element)); }
Explanation: The .every()
method tests whether all elements in the elements
array are present in the arr
.
Challenge 30: Find the Median
Task: Write a function to find the median of an array of numbers.
Example:
findMedian([1, 2, 3, 4, 5]); // 3
Solution:
function findMedian(arr) { arr.sort((a, b) => a - b); const mid = Math.floor(arr.length / 2); return arr.length % 2 !== 0 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2; }
Explanation: First, sort the array. If the length is odd, return the middle element. If even, return the average of the two middle elements.
These challenges should give you a thorough workout in array manipulation techniques. By solving them, you’ll improve your ability to handle various array-related tasks in JavaScript. Enjoy coding!