Day 24/30 – Sort an Array by Function Output in JavaScript Challange🔢 | Custom Comparator 📌 Problem Given: An array arr A function fn Return a new array sortedArr sorted in ascending order based on the value returned by fn(arr[i]). You can assume: fn always returns a number Sorting must be based on fn output 🧠 Example arr = [5, 4, 1, 2, 3] fn = (x) => x * x Since squares are: 25, 16, 1, 4, 9 Sorted by square value: [1, 2, 3, 4, 5] 💡 JavaScript Solution var sortBy = function(arr, fn) { return arr.slice().sort((a, b) => fn(a) - fn(b)); }; 🔎 Why This Works sort() accepts a comparator fn(a) - fn(b) ensures ascending order slice() prevents mutation of the original array Time Complexity: O(n log n) Space Complexity: O(n) (due to copy) ⚡ Real-World Use Cases Sorting users by age Sorting products by price Ranking students by score Sorting tasks by priority 🧠 Interview Insight This pattern is called “sort by projection”: You don’t sort by the element itself — You sort by a derived value. That’s a powerful abstraction concept. #JavaScript #30DaysOfJavaScript #CodingChallenge #JSLogic #ArrayMethods #WebDevelopment #FrontendDevelopment #LearnToCode #CodeEveryday #Programming #DeveloperJourney #TechCommunity #InterviewPrep #LeetCode #AsyncJavaScript #SoftwareEngineering #100DaysOfCode #BuildInPublic Custom comparator JavaScript Sort array by derived value JS JavaScript array sort interview question Higher order functions JavaScript JavaScript sorting techniques JS sort with callback Advanced JavaScript array methods JavaScript coding challenge solution Frontend interview preparation
Sort Array by Custom Comparator in JavaScript
More Relevant Posts
-
🚀 Understanding "var" Scope in JavaScript In JavaScript, there are mainly three types of scope: 1️⃣ Global Scope – Variables declared outside any function are accessible everywhere in the program. 2️⃣ Function Scope – Variables declared inside a function can only be used inside that function. 3️⃣ Block Scope – Variables declared inside blocks like "{ }" (for example in "if", "for", etc.) are only accessible inside that block. However, the important thing to remember is: 👉 The "var" keyword only follows Global Scope and Function Scope. ❌ It does NOT follow Block Scope. Let’s look at a simple example: if (true) { var message = "Hello World"; } console.log(message); // Output: Hello World Even though "message" is declared inside the "if" block, we can still access it outside the block. This happens because "var" ignores block scope. Now look at a function example: function test() { var number = 10; console.log(number); // 10 } console.log(number); // Error: number is not defined Here, "number" is declared inside the function, so it cannot be accessed outside the function. ✅ Key Takeaway: - "var" → Global Scope + Function Scope - "var" ❌ does not support Block Scope That’s why modern JavaScript developers prefer "let" and "const", because they properly support block scope. #JavaScript #WebDevelopment #Programming #BackendDevelopment
To view or add a comment, sign in
-
I’ve lost count of how many times I’ve seen the same explanation: “Primitives are passed by value, objects by reference.” It’s everywhere—in tutorials, interviews, Stack Overflow answers… and honestly, it’s been driving me nuts because it’s not quite accurate in JavaScript. So I finally sat down and wrote the post I wish I’d read years ago: “Primitives vs Objects: How JavaScript Values Actually Work” The real difference isn’t “value vs reference”—it’s mutability. Primitives are immutable (you can’t change them, only replace them). Objects are mutable (you can change their contents, and everyone with a reference sees it). Everything else flows from there: why a = b behaves differently, why {} === {} is false, why mutating an object affects the “original”, why reassignment doesn’t, and even why JavaScript technically uses “call by sharing” for everything. If you’ve ever been confused by why changing an array in a function changes the original, or why strings act “weird” compared to objects—this might clear things up. Check it out here: https://lnkd.in/dvRfbPFC What’s the biggest JavaScript primitive/object misconception you’ve had to unlearn? Drop it below—I’m curious. 👇 #JavaScript #WebDevelopment #Programming #Frontend
To view or add a comment, sign in
-
🚀 **JavaScript: var vs let vs const (Explained Clearly)** If you're learning JavaScript or preparing for interviews, this is a concept you MUST understand 👇 --- ## 🔹 var ```js var name = "Ali"; var name = "Ahmed"; // ✅ Allowed name = "John"; // ✅ Allowed ``` ✔ Function scoped ✔ Can be redeclared ✔ Can be updated ⚠ Problem: Can cause unexpected bugs due to scope issues. --- ## 🔹 let ```js let name = "Ali"; let name = "Ahmed"; // ❌ Error name = "John"; // ✅ Allowed ``` ✔ Block scoped ❌ Cannot be redeclared in same scope ✔ Can be updated ✅ Use when the value needs to change. --- ## 🔹 const ```js const name = "Ali"; name = "Ahmed"; // ❌ Error ``` ✔ Block scoped ❌ Cannot be redeclared ❌ Cannot be reassigned ✅ Use by default in modern JavaScript. --- ## 💡 Best Practice (Modern JS Rule) 👉 Use **const** by default 👉 Use **let** when value needs to change 👉 Avoid **var** --- ### 🎯 Interview Tip Most scope-related bugs happen because of `var`. Understanding block scope vs function scope makes you a stronger developer. --- https://lnkd.in/gzGAbU8A 💬 Quick question: Do you still use `var` in your projects? #JavaScript #FrontendDevelopment #WebDevelopment #Programming #CodingInterview #JSConcepts #SoftwareEngineering #FullStackDeveloper #LearnToCode #DeveloperTips #100DaysOfCode #TechCommunity
To view or add a comment, sign in
-
-
Best JavaScript Interview Question: 🚀 The Sneaky Semicolon That Changed My Array! We’ve all been there: staring at a piece of JavaScript code, wondering why the output isn’t what we expected. Sometimes, the culprit is as small as a semicolon. Let’s look at this classic example: const length = 4; const numbers = []; for (var i = 0; i < length; i++) { numbers.push(i + 1); } console.log(numbers); // [1, 2, 3, 4] ✅ Without the semicolon, everything works as expected. The loop runs 4 times, pushing 1, 2, 3, 4 into the array. Now watch what happens when we accidentally add a semicolon after the for loop: const length = 4; const numbers = []; for (var i = 0; i < length; i++); { // <- sneaky semicolon! numbers.push(i + 1); } console.log(numbers); // [5] 😱 Suddenly, instead of [1, 2, 3, 4], we get [5]. Why does this happen? 1. That semicolon ends the loop immediately. 2. The loop runs, incrementing i until it reaches 4. 3. The block { numbers.push(i + 1); } is no longer part of the loop — it executes once after the loop finishes. At that point, i is 4, so i + 1 is 5. Result: [5]. Key Takeaways 1. A stray semicolon can completely change your program’s logic. 2. Always be mindful of where you place semicolons in JavaScript. 3. Tools like ESLint can catch these mistakes before they cause headaches. Prefer let or const over var to avoid scope confusion. 💡 Pro Tip: If you’ve ever debugged for hours only to find a tiny typo or semicolon was the issue, you’re not alone. Share this with your network , it might save someone else from a late‑night debugging session! Follow me for more such learning. #javascript #debuging #webdeveloper #frontenddeveloper #codewithramkumar
To view or add a comment, sign in
-
💡 JavaScript Array Methods Every Developer Must Know If you want to write cleaner, shorter, and more readable JavaScript code, mastering array methods is non-negotiable. Array methods not only simplify logic but also help you write functional, scalable, and interview-ready code. 🚀 Here are some essential array methods every developer should master: 🔹 Transformation & Iteration ✅ "map()" → Transform each element ✅ "forEach()" → Iterate without returning a new array ✅ "flatMap()" → Map + flatten in one step 🔹 Filtering & Searching ✅ "filter()" → Get elements based on condition ✅ "find()" → First matching element ✅ "findIndex()" → Index of matching element ✅ "some()" → Check if at least one element matches ✅ "every()" → Check if all elements match 🔹 Aggregation & Utilities ✅ "reduce()" → Powerful method for totals, grouping & complex logic ✅ "sort()" → Sort elements (numbers/strings/custom logic) ✅ "includes()" → Check if value exists ✅ "indexOf()" / "lastIndexOf()" → Find element position 🔹 Modification Methods ✅ "push()" / "pop()" → Add or remove from end ✅ "shift()" / "unshift()" → Add or remove from start ✅ "splice()" → Add/remove elements anywhere ✅ "slice()" → Copy portion of array without mutation 🔥 Why these methods matter 👉 Improve code readability 👉 Reduce loops & boilerplate logic 👉 Essential for React state updates 👉 Frequently asked in JavaScript interviews 👉 Useful in real-world data transformation As a React developer, I use these methods daily for state updates, API data transformation, and UI rendering logic. Consistency in practicing these methods can dramatically level up your problem-solving and coding confidence. 💬 Which array method do you use the most? Comment below 👇 #JavaScript #ArrayMethods #JSBasics #FrontendDevelopment #WebDevelopment #ReactJS #CodingTips #LearnInPublic
To view or add a comment, sign in
-
Understanding "let" Scope in JavaScript (Global, Function, and Block Scope) 1️⃣ Global Scope When a variable is declared outside any function or block using "let", it becomes a global variable and can be accessed anywhere in the program. let username = "Ali"; function showUser() { console.log(username); } showUser(); // Ali Here, "username" is declared globally, so it can be accessed inside the function as well. --- 2️⃣ Function Scope When "let" is declared inside a function, it can only be accessed within that function. function test() { let number = 10; console.log(number); // 10 } test(); console.log(number); // Error: number is not defined The variable "number" only exists inside the function "test()". --- 3️⃣ Block Scope One of the biggest advantages of "let" is block scope. If a variable is declared inside a block "{ }", it can only be used inside that block. if (true) { let message = "Hello"; console.log(message); // Hello } console.log(message); // Error: message is not defined Here, "message" is limited to the "if" block only. --- ✅ Key Point - "let" respects Global Scope - "let" respects Function Scope - "let" respects Block Scope Because of this predictable behavior, developers prefer "let" and "const" over "var" in modern JavaScript. 💡 Understanding scope helps you write cleaner and more reliable code. #JavaScript #WebDevelopment #BackendDevelopment #Programming
To view or add a comment, sign in
-
⚡ Top 14 JavaScript Array Methods Every Developer Should Know If you’re learning JavaScript or preparing for frontend interviews, array methods are used everywhere. Understanding them well can make your code cleaner, shorter, and more efficient. Here are 14 essential JavaScript array methods worth mastering 👇 📌 Core Array Operations .push() ↳ Adds one or more elements to the end of an array. .pop() ↳ Removes the last element from an array. .shift() ↳ Removes the first element from an array. .unshift() ↳ Adds one or more elements to the beginning of an array. 📌 Array Modification & Extraction .slice() ↳ Extracts a portion of an array into a new array. .splice() ↳ Adds, removes, or replaces elements inside an array. 📌 Transformation & Iteration .map() ↳ Creates a new array by transforming each element. .filter() ↳ Creates a new array with elements that match a condition. .reduce() ↳ Reduces the array to a single value using a function. .forEach() ↳ Executes a function on each element (no return value). 📌 Searching & Checking .find() ↳ Returns the first element that matches a condition. .findIndex() ↳ Returns the index of the first matching element. .includes() ↳ Checks if an array contains a specific value. 📌 Sorting .sort() ↳ Sorts the elements of an array in place. 💡 Pro tip: In real-world frontend development, methods like map, filter, and reduce are used heavily in frameworks like React. If this helped, save it for quick revision. #JavaScript #FrontendDevelopment #WebDevelopment #Coding #Programming #ReactJS #TechLearning
To view or add a comment, sign in
-
Most developers first meet Continuation-Passing Style without realizing it. If you have ever written a callback in JavaScript, you have already used it. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗖𝗼𝗻𝘁𝗶𝗻𝘂𝗮𝘁𝗶𝗼𝗻-𝗣𝗮𝘀𝘀𝗶𝗻𝗴 𝗦𝘁𝘆𝗹𝗲? Continuation-Passing Style (CPS) is a pattern where a function does not return a result directly. Instead, it receives another function, called a continuation, and passes the result to it. Instead of saying: "Here is the result" we say: "When you are ready, call this function with the result" 𝗛𝗼𝘄 𝘄𝗲 𝗻𝗼𝗿𝗺𝗮𝗹𝗹𝘆 𝘄𝗿𝗶𝘁𝗲 𝗶𝘁: function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } const sum = add(2, 3); const result = multiply(sum, 4); console.log(result); 𝗖𝗣𝗦 𝘃𝗲𝗿𝘀𝗶𝗼𝗻: function add(a, b, continuation) { continuation(a + b); } function multiply(a, b, continuation) { continuation(a * b); } add(2, 3, (sum) => { multiply(sum, 4, (product) => { console.log(product); }); }); The functions no longer return values. They pass control forward. 𝗪𝗵𝘆 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹? Because execution flow becomes explicit. Instead of relying on the call stack and returns, we decide what happens next. This makes CPS especially useful for: • Asynchronous operations • Non-blocking execution • Error handling • Custom control flow • Building interpreters and compilers Before Promises and async/await, JavaScript relied heavily on this model. 𝗪𝗵𝗮𝘁 𝗮𝗯𝗼𝘂𝘁 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗵𝗲𝗹𝗹? CPS gives powerful control over execution flow. But without proper composition it can lead to deeply nested callbacks, often called "callback hell". That was not a flaw of the idea itself. It was a signal that we needed better abstractions. Promises and async/await did not replace CPS. They abstracted it. Every then is a continuation. Every await compiles down to continuation logic under the hood. Understanding CPS helps you: • Understand how async actually works • Reason about execution order • Appreciate modern abstractions • Think more clearly about control flow The next time you write async/await, remember: there is a continuation hiding underneath. #JavaScript #FunctionalProgramming #ComputerScience #SoftwareEngineering
To view or add a comment, sign in
-
Say Goodbye to JavaScript Date Object Headaches! For years, developers have struggled with the built-in Date object in JavaScript—it's mutable, inconsistent, and a major pain when dealing with time zones or complex date arithmetic. Most of us have relied on external libraries like Moment.js or date-fns to get the job done. But the future is here: the Temporal API is arriving as a new built-in standard, and it's a game-changer! 🚀 Temporal provides a robust, modern, and reliable way to handle dates and times. Here’s why you should be excited: 🔒 Immutability: Every Temporal object is immutable, which eliminates a major source of bugs in date manipulation. 🌍 First-Class Time Zones: It has explicit, robust support for time zones and daylight saving time (DST). ➗ Safe Arithmetic: Performing calculations like adding or subtracting days is predictable and straightforward with methods like add() and subtract(). 🎯 Clear Data Types: Instead of one generic Date object, Temporal offers distinct types for different use cases: Instant: For exact points in time. PlainDate, PlainTime, PlainDateTime: For wall-clock dates and times without a specific time zone. ZonedDateTime: For handling time-zoned timestamps. Major browsers are actively implementing the proposal. You can start experimenting with it today using a polyfill or check out the official TC39 documentation. It's time to level up our date-handling skills! Who's ready to make the switch? #JavaScript #WebDev #Frontend #Temporal #Programming #Coding #TechNews
To view or add a comment, sign in
-
-
Understanding "NaN" in JavaScript (Not a Number) Let’s understand it in a simple way. --- What is "NaN"? "NaN" stands for Not a Number. It is a special value in JavaScript that appears when JavaScript tries to perform a numeric operation but cannot produce a valid number. In simple words: When JavaScript fails to convert something into a number during a mathematical operation, the result becomes "NaN". --- Example 1: Invalid Number Conversion console.log("hello" - 5); // NaN Here JavaScript tries to convert ""hello"" into a number to perform subtraction. Since ""hello"" cannot be converted into a number, the result becomes NaN. --- Example 2: Parsing a Non-Numeric Value console.log(parseInt("abc")); // NaN ""abc"" cannot be converted into a numeric value, so JavaScript returns NaN. --- Example 3: Invalid Mathematical Result console.log(0 / 0); // NaN Mathematically, "0 / 0" does not produce a valid number, so JavaScript returns NaN. --- Important Thing to Remember Some developers think "NaN" appears when a variable does not exist, but that is not true. If a variable does not exist, JavaScript throws a ReferenceError, not "NaN". Example: console.log(score); // ReferenceError: score is not defined --- Key Takeaway NaN → When a numeric operation cannot produce a valid number Not because a variable doesn’t exist Simple rule to remember: - Invalid numeric operation → NaN - Variable not defined → ReferenceError #JavaScript #WebDevelopment #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
Explore related topics
- Approaches to Array Problem Solving for Coding Interviews
- Common Algorithms for Coding Interviews
- Advanced React Interview Questions for Developers
- Solving Sorted Array Coding Challenges
- LeetCode Array Problem Solving Techniques
- Front-end Development with React
- Prioritizing Problem-Solving Skills in Coding Interviews
- How to Use Arrays in Software Development
- How to Rank Tasks for Better Work Efficiency
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