Created
November 12, 2024 08:22
-
-
Save GlistenSTAR/0e60c62bf8725bbc3241b9ac6665d12d to your computer and use it in GitHub Desktop.
Some JS script in Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. How Do You Find the Largest Number in an Array? | |
function findLargest(arr) { | |
return Math.max(...arr); | |
} | |
console.log(findLargest([1, 5, 3, 9, 2])); // 9 | |
2. How Do You Find the Second Largest Number in an Array? | |
function secondLargest(arr) { | |
let sorted = arr.sort((a, b) => b - a); | |
return sorted[1]; | |
} | |
console.log(secondLargest([1, 5, 3, 9, 7])); // 7 | |
3. How Do You Remove Duplicates from an Array? | |
function removeDuplicates(arr) { | |
return [...new Set(arr)]; | |
} | |
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5] | |
4. How Do You Merge Two Sorted Arrays? | |
function mergeArrays(arr1, arr2) { | |
return arr1.concat(arr2).sort((a, b) => a - b); | |
} | |
console.log(mergeArrays([1, 3, 5], [2, 4, 6])); // [1, 2, 3, 4, 5, 6] | |
5. How Do You Rotate an Array? | |
function rotateArray(arr, k) { | |
k = k % arr.length; // Handle cases where k > array length | |
return arr.slice(-k).concat(arr.slice(0, -k)); | |
} | |
console.log(rotateArray([1, 2, 3, 4, 5], 2)); // [4, 5, 1, 2, 3] | |
6. How Do You Check if Two Arrays Are Equal? | |
function arraysEqual(arr1, arr2) { | |
if (arr1.length !== arr2.length) return false; | |
for (let i = 0; i < arr1.length; i++) { | |
if (arr1[i] !== arr2[i]) return false; | |
} | |
return true; | |
} | |
console.log(arraysEqual([1, 2, 3], [1, 2, 3])); // true | |
console.log(arraysEqual([1, 2, 3], [1, 2, 4])); // false | |
7. How Do You Find All Pairs in an Array That Sum to a Specific Value? | |
function findPairs(arr, target) { | |
let result = []; | |
let seen = new Set(); | |
for (let num of arr) { | |
let complement = target - num; | |
if (seen.has(complement)) { | |
result.push([num, complement]); | |
} | |
seen.add(num); | |
} | |
return result; | |
} | |
console.log(findPairs([2, 4, 3, 5, 7, 8, 9], 10)); // [[7, 3], [8, 2], [9, 1]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GOOD JOBS. :)))