Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

📚 A list of popular JavaScript algorithms that you'll encounter in the real world. 🧠

License

NotificationsYou must be signed in to change notification settings

AllThingsSmitty/javascript-algorithms

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 

Repository files navigation

This repository contains a curated list of JavaScript algorithms, organized by category. These range from simple string manipulation to advanced searching and sorting techniques — perfect for interviews and foundational learning.

Note

Popularity is based on common interview topics, educational materials, and developer community usage.

Algorithms

String Manipulation

Math & Number Theory

Searching

Sorting

Array Utilities

Utility Functions

String Manipulation

Reverse a String

functionreverseString(str){returnstr.split("").reverse().join("");}console.log(reverseString("hello"));// Output: "olleh"

Explanation: Reverses the characters in a string by splitting, reversing, and joining them back together.

Back to top

Palindrome Check

functionisPalindrome(str){returnstr===str.split("").reverse().join("");}console.log(isPalindrome("racecar"));// Output: true

Explanation: Determines if a string reads the same backward as forward using string reversal.

Back to top

Character Frequency Counter

functioncharFrequency(str){constfreq={};for(letcharofstr){freq[char]=(freq[char]||0)+1;}returnfreq;}console.log(charFrequency("hello"));// Output: { h: 1, e: 1, l: 2, o: 1 }

Explanation: Counts how often each character appears in a string.

Back to top

Anagram Check

functionisAnagram(str1,str2){constnormalize=(str)=>str.split("").sort().join("");returnnormalize(str1)===normalize(str2);}console.log(isAnagram("listen","silent"));// Output: true

Explanation: Determines if two strings are anagrams by sorting and comparing them.

Back to top

Math & Number Theory

Prime Number Check

functionisPrime(num){if(num<=1)returnfalse;for(leti=2;i<=Math.sqrt(num);i++){if(num%i===0)returnfalse;}returntrue;}console.log(isPrime(7));// Output: true

Explanation: Checks if a number is prime by testing divisibility up to its square root.

Back to top

Fibonacci Sequence (Recursive)

functionfibonacci(n){if(n<=1)returnn;returnfibonacci(n-1)+fibonacci(n-2);}console.log(fibonacci(6));// Output: 8

Explanation: Generates the nth Fibonacci number recursively by summing the two preceding numbers.

⚠️Note: This approach has exponential time complexityO(2^n) and is inefficient for large inputs.

Back to top

Factorial of a Number

functionfactorial(n){if(n<0)thrownewRangeError("Factorial is not defined for negative numbers");if(n===0||n===1)return1;returnn*factorial(n-1);}console.log(factorial(5));// Output: 120

Explanation: Calculates the factorial of a number recursively by multiplying it with decremented values.

Back to top

Find the GCD (Greatest Common Divisor)

functiongcd(a,b){if(b===0)returna;returngcd(b,a%b);}console.log(gcd(48,18));// Output: 6

Explanation: Uses the Euclidean algorithm to compute the greatest common divisor.

Back to top

Searching

Two Sum (Using Hash Map)

functiontwoSum(nums,target){constmap=newMap();for(leti=0;i<nums.length;i++){constcomplement=target-nums[i];if(map.has(complement))return[map.get(complement),i];map.set(nums[i],i);}return[];}console.log(twoSum([2,7,11,15],9));// Output: [0, 1]

Explanation: Finds two indices such that their values sum to the target using a hash map.

Back to top

Binary Search

functionbinarySearch(arr,target){letleft=0,right=arr.length-1;while(left<=right){constmid=Math.floor((left+right)/2);if(arr[mid]===target)returnmid;if(arr[mid]<target)left=mid+1;elseright=mid-1;}return-1;}console.log(binarySearch([1,2,3,4,5],4));// Output: 3

Explanation: Searches for a target in a sorted array using a divide-and-conquer approach.

Back to top

Sorting

Bubble Sort

functionbubbleSort(arr){for(leti=0;i<arr.length;i++){for(letj=0;j<arr.length-i-1;j++){if(arr[j]>arr[j+1]){[arr[j],arr[j+1]]=[arr[j+1],arr[j]];}}}returnarr;}console.log(bubbleSort([5,3,8,4,2]));// Output: [2, 3, 4, 5, 8]

Explanation: Sorts an array by repeatedly swapping adjacent elements if they are in the wrong order.

Back to top

Quick Sort

functionquickSort(arr){if(arr.length<=1)returnarr;constpivot=arr[arr.length-1];constleft=[],right=[];for(leti=0;i<arr.length-1;i++){if(arr[i]<pivot)left.push(arr[i]);elseright.push(arr[i]);}return[...quickSort(left),pivot, ...quickSort(right)];}console.log(quickSort([3,6,8,10,1,2,1]));// Output: [1, 1, 2, 3, 6, 8, 10]

Explanation: A divide-and-conquer sorting algorithm with an average-case time complexity ofO(n log n).

Back to top

Merge Two Sorted Arrays

functionmergeSortedArrays(arr1,arr2){letmerged=[],i=0,j=0;while(i<arr1.length&&j<arr2.length){if(arr1[i]<arr2[j]){merged.push(arr1[i++]);}else{merged.push(arr2[j++]);}}returnmerged.concat(arr1.slice(i)).concat(arr2.slice(j));}console.log(mergeSortedArrays([1,3,5],[2,4,6]));// Output: [1, 2, 3, 4, 5, 6]

Explanation: Merges two sorted arrays into one sorted array by comparing elements sequentially.

Back to top

Array Utilities

Find Maximum in Array

functionfindMax(arr){returnMath.max(...arr);}console.log(findMax([1,2,3,4,5]));// Output: 5

Explanation: Finds the largest number in an array using theMath.max function and spread operator.

Back to top

Utility Functions

Debounce Function

functiondebounce(fn,delay){lettimer;returnfunction(...args){clearTimeout(timer);timer=setTimeout(()=>fn.apply(this,args),delay);};}constlog=debounce(()=>console.log("Debounced!"),300);log();log();log();// Logs once after 300ms of inactivity

Explanation: Limits the rate at which a function can fire, commonly used in event handling (e.g., input, scroll).

Back to top


[8]ページ先頭

©2009-2025 Movatter.jp