Top Practice Problems of Array
1. Find the Second Largest Number in an Array
function secondLargest(arr) {
if (arr.length < 2) return null; // If there are less than 2 elements, return null
let first = arr[0]; // Assume first element is the largest
let second = -Infinity; // Initially set second largest as very small
for (let i = 1; i < arr.length; i++) {
if (arr[i] > first) {
second = first; // Move the current largest to second
first = arr[i]; // Update the largest
} else if (arr[i] > second && arr[i] !== first) {
second = arr[i]; // Update second if it's smaller than first but greater than previous second
}
}
return second === -Infinity ? null : second; // If no second largest, return null
}
console.log(secondLargest([10, 5, 20, 8])); // Output: 10
console.log(secondLargest([3, 3, 3, 3])); // Output: null
console.log(secondLargest([5])); // Output: null
2. Remove Duplicates from an Array in JS
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
// Output: [1, 2, 3, 4, 5]
3. Find the Intersection of Two Arrays
function arrayIntersection(arr1, arr2) {
return arr1.filter(value => arr2.includes(value));
}
console.log(arrayIntersection([1, 2, 3, 4], [3, 4, 5, 6])); // Output: [3, 4]
console.log(arrayIntersection(["apple", "banana"], ["banana", "grape"])); // Output: ["banana"]
4. Find the Maximum Number in a Array in JS
function findMax(arr) {
if (arr.length === 0) return undefined; // Handle empty array case
let max = arr[0]; // Initialize max with the first element
for (let i = 1; i < arr.length; i++) { // Start loop from the second element
if (arr[i] > max) {
max = arr[i]; // Update max if a larger number is found
}
}
return max;
}
console.log(findMax([10, 5, 20, 8, 30])); // Output: 30
console.log(findMax([-3, -1, -7, -2])); // Output: -1
console.log(findMax([])); // Output: undefined
5. Find Sum of all elements in an array using a for loop
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i]; // Adding each element to sum
}
return sum;
}
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15