Day 9 / 30 - Javascript Coding Problem: Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element. This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The ultimate value of val is then returned. If the length of the array is 0, the function should return init. Please solve it without using the built-in Array.reduce method. Solution: var reduce = function (nums, fn, init) { let numsLength = nums?.length; if (numsLength === 0) { return init; } let acc = init; for (let k = 0; k < numsLength; k++) { acc = fn(acc, nums[k]); } return acc; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment #ProblemSolving
Implement Array Reduce Function in JavaScript
More Relevant Posts
-
Day 6 / 30 - JavaScript Coding Practice Today’s problem: Roman to Integer var romanToInt = function (s) { if (s.length > 15) { return; } const romanMap = new Map([ ['I', 1], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['D', 500], ['M', 1000] ]); let sum = 0; let preValue = 0; for (let k = s.length - 1; k >= 0; k--) { let currentVal = romanMap.get(s[k]); if (currentVal < preValue) { sum -= currentVal; } else { sum += currentVal; } preValue = currentVal; } return sum; }; 💡 Key Insight: Instead of scanning from left to right, I iterated from right to left to easily handle subtraction cases like IV (4) and IX (9). 👉 If a smaller value comes before a larger one → subtract 👉 Otherwise → add #JavaScript #DSA #CodingPractice #ProblemSolving #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
Day 19 / 30 – JavaScript Coding Challenge Problem: Given two strings, needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if it doesn’t exist. Solution: var strStr = function (haystack, needle) { if (needle.length === 0) return -1 for (let i = 0; i <= haystack.length - needle.length; i++) { let found = true; for (let j = 0; j < needle.length; j++) { if (haystack[i + j] !== needle[j]) { found = false; break; } } if (found) { return i } } return -1; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #ProblemSolving #FrontendDevelopment
To view or add a comment, sign in
-
-
Day 15 / 30 - Javascript Coding practice Problem : Longest Common Prefix Find the longest common prefix among an array of strings. If there’s no common prefix, return an empty string "". Solution: var longestCommonPrefix = function (strs) { let longestStr = strs[0] for (let k = 1; k < strs.length; k++) { let j = 0; while (j < strs[k].length && j < longestStr.length && strs[k][j] === longestStr[j]) { j++; } longestStr = longestStr.slice(0, j) if (longestStr === "") return "" } return longestStr; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #ProblemSolving #FrontendDevelopment
To view or add a comment, sign in
-
-
Day 20 / 30 – JavaScript Coding Challenge Today’s problem: Length of Last Word Problem: Given a string containing words and spaces, return the length of the last word. Solution: var lengthOfLastWord = function (s) { let count = 0; let i = s.length - 1; while (i >= 0 && s[i] === " ") { i--; } while (i >= 0 && s[i] !== " ") { i--; count++; } return count; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #ProblemSolving #FrontendDevelopment
To view or add a comment, sign in
-
-
Day 10 / 30 - Javascript Coding Challenge Problem: Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions. The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). The function composition of an empty list of functions is the identity function f(x) = x. You may assume each function in the array accepts one integer as input and returns one integer as output. Solution: var compose = function (functions) { return function (x) { let sum = x; for (let k = functions.length - 1; k >= 0; k--) { sum = functions[k](sum) } return sum } }; #JavaScript #FunctionalProgramming #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
🧠 JavaScript Myth Busting: "Let and Const are not Hoisted" (Yes, they are!) Have you ever been told in an interview that "let" and "const" aren’t hoisted, but "var" is? It’s one of the most common misconceptions in JavaScript. 👉 Here is the 100% technical truth: All declarations in JavaScript ("var", "let", "const", "function", "class") are hoisted. So, why do they behave differently? It’s all about Initialization and a friendly little neighborhood called the Temporal Dead Zone (TDZ). --- 🚨 The Difference: 1️⃣ "var" is hoisted AND initialized immediately with the value of "undefined". You can access it before its line of code without crashing. 2️⃣ "let" and "const" are hoisted BUT NOT initialized. The JavaScript engine knows they exist, but it reserves the memory without setting any starting value. --- 💀 Enter the Temporal Dead Zone (TDZ): The TDZ is the period of time between the start of a block and the moment the variable is actually initialized (the line where you wrote the declaration in your code). If you try to touch a "let" or "const" variable while it is trapped in the TDZ, JavaScript throws a ReferenceError. --- 💡 Why does this matter? The TDZ exists to enforce better coding practices. It helps prevent bugs by stopping you from using variables that have been created but aren't yet ready for use. --- 📌 Check out the image below for a simple breakdown! 👇 💬 Drop your best analogies in the comments! #javascript #coding #webdevelopment #programmingmyths #softwareengineering #learncoding #frontend
To view or add a comment, sign in
-
-
Day 17 / 30 – JavaScript Coding Challenge Problem: Remove duplicates in-place from a sorted array and return the count of unique elements. Solution: var removeDuplicates = function (nums) { if (nums.length === 0) return 0; let i = 0; for (let j = 0; j < nums.length; j++) { if (nums[j] !== nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }; #JavaScript #DSA #CodingPractice #100DaysOfCode #ProblemSolving #FrontendDevelopment
To view or add a comment, sign in
-
-
Scope vs Closure in JavaScript — Explained Simply Understanding the difference between Scope and Closure is crucial for writing clean and efficient JavaScript code. While Scope defines where variables are accessible, Closure allows functions to remember their lexical environment even after execution. This concept is widely used in: • Data encapsulation • Function factories • Callbacks & async programming If you’ve ever been confused between these two, this guide will help you clear it with practical examples. 👉 Read the full article: https://lnkd.in/ga8WaNiA #JavaScript #FrontendDevelopment #WebDevelopment #Programming #Coding #SoftwareDevelopment #LearnJavaScript #InterviewPrep
To view or add a comment, sign in
-
Some JavaScript concepts sound simple but create confusion in real projects. One common example is Debounce vs Throttle. Both are used to control how frequently a function executes when events happen repeatedly, such as scrolling, resizing, or typing in an input field. Understanding the difference helps developers build better-performing and more responsive applications. In this article, I explained the concept with simple examples so developers can easily understand when to use Debounce and when to use Throttle. Read the article: Debounce vs Throttle in JavaScript https://lnkd.in/gK5NE4Cn #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareDevelopment #Programming #Coding
To view or add a comment, sign in
-
⚡ Why map() Can Be Slower Than a for Loop in JavaScript As developers, we often prefer clean and functional code using methods like map(). But when it comes to performance, especially with large datasets, a traditional for loop can sometimes outperform it. In this article, I break down: • The internal working of map() • Performance comparison with for loops • When readability > performance • Best practices for real-world applications 📌 Understanding these differences helps you write more optimized and scalable JavaScript code. 👉 Read the full article here: https://lnkd.in/gp56bXJc 💡 What’s your go-to approach for iteration in JavaScript? #JavaScript #SoftwareDevelopment #WebDevelopment #FrontendDevelopment #Programming #Coding #PerformanceOptimization #Tech
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development