Mastering JavaScript Arrays with Practical Examples

🚀 Expanding My Programming Skills with JavaScript Arrays! After working on Python fundamentals, I’ve now started practicing **array-based programs in JavaScript** to strengthen my problem-solving skills and explore a new language. 💻✨ In this article, I’ve covered different array concepts such as: ✔️ Finding common and unique elements ✔️ Array merging, union & intersection ✔️ Moving zeros and handling edge cases ✔️ Finding pairs with a given sum ✔️ Sorting without built-in functions ✔️ Identifying majority and non-repeating elements This practice is helping me improve my logical thinking and understand how similar concepts work across different programming languages. Consistency and small efforts every day are helping me grow step by step 🚀 #JavaScript #CodingJourney #DataStructures #Programming #Learning #WebDevelopment #100DaysOfCode 1️⃣ Find Common Elements in Two Arrays let arr1 = [1, 2, 3, 4]; let arr2 = [3, 4, 5, 6]; let common = arr1.filter(num => arr2.includes(num)); console.log("Common Elements:", common); 2️⃣ Merge Two Arrays Without Duplicates let arr1 = [1, 2, 3]; let arr2 = [3, 4, 5]; let merged = [...new Set([...arr1, ...arr2])]; console.log("Merged Array:", merged); 3️⃣ Find the Largest Difference let arr = [2, 3, 10, 6, 4, 8, 1]; let min = arr[0]; let maxDiff = 0; for (let i = 1; i < arr.length; i++) { if (arr[i] - min > maxDiff) { maxDiff = arr[i] - min; } if (arr[i] < min) { min = arr[i]; } } console.log("Max Difference:", maxDiff); 4️⃣ Move All Zeros to End let arr = [0, 1, 0, 3, 12]; let result = arr.filter(num => num !== 0).concat(arr.filter(num => num === 0)); console.log("Result:", result); 5️⃣ Find Intersection of Arrays let arr1 = [1, 2, 2, 3]; let arr2 = [2, 2, 4]; let intersection = arr1.filter(num => arr2.includes(num)); console.log("Intersection:", intersection); 6️⃣ Find Union of Two Arrays let arr1 = [1, 2, 3]; let arr2 = [2, 3, 4]; let union = [...new Set([...arr1, ...arr2])]; console.log("Union:", union); 7️⃣ Find First Non-Repeating Element let arr = [4, 5, 1, 2, 0, 4]; let freq = {}; for (let num of arr) { freq[num] = (freq[num] || 0) + 1; } for (let num of arr) { if (freq[num] === 1) { console.log("First Non-Repeating:", num); break; } } 8️⃣ Find Pairs with Given Sum let arr = [1, 5, 7, -1, 5]; let target = 6; for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === target) { console.log(arr[i], arr[j]); } } } 9️⃣ Sort Array Without Built-in Function (Bubble Sort) let arr = [5, 3, 8, 4, 2]; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } console.log("Sorted Array:", arr);

To view or add a comment, sign in

Explore content categories