JavaScript snippets
Small JavaScript functions for arrays, objects, strings, dates and the browser DOM, each with a short explanation and an example call.
Short third-party examples with no input validation or error handling. Browser snippets assume a DOM and do not run in Node.js. Check whether the language now has a built-in (Array.prototype.at, structuredClone, Object.groupBy) before copying one. See TypeScript for typed equivalents.
- accumulateCreates an array of partial sums.
- addClassAdds a class to an HTML element.
- addDaysToDateCalculates the date of n days from the given date, returning its string representation.
- addEventListenerAllAttaches an event listener to all the provided targets.
- addMinutesToDateCalculates the date of n minutes from the given date, returning its string representation.
- addMultipleListenersAdds multiple event listeners with the same handler to an element.
- addStylesAdds the provided styles to the given element.
- addWeekDaysCalculates the date after adding the given number of business days.
- allChecks if the provided predicate function returns true for all elements in a collection.
- allEqualChecks if all elements in an array are equal.
- allEqualByChecks if all elements in an array are equal, based on the provided mapping function.
- allUniqueChecks if all elements in an array are unique.
- allUniqueByChecks if all elements in an array are unique, based on the provided mapping function.
- andChecks if both arguments are true.
- anyChecks if the provided predicate function returns true for at least one element in a collection.
- apertureCreates an array of n-tuples of consecutive elements.
- approximatelyEqualChecks if two numbers are approximately equal to each other.
- arithmeticProgressionCreates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.
- arrayToCSVConverts a 2D array to a comma-separated values (CSV) string.
- arrayToHTMLListConverts the given array elements into <li> tags and appends them to the list of the given id.
- aryCreates a function that accepts up to n arguments, ignoring any additional arguments.
- assertValidKeysValidates all keys in an object match the given keys.
- atobDecodes a string of data which has been encoded using base-64 encoding.
- attemptAttempts to invoke a function with the provided arguments, returning either the result or the caught error object.
- averageCalculates the average of two or more numbers.
- averageByCalculates the average of an array, after mapping each element to a value using the provided function.
- bifurcateSplits values into two groups, based on the result of the given filter array.
- bifurcateBySplits values into two groups, based on the result of the given filtering function.
- binaryCreates a function that accepts up to two arguments, ignoring any additional arguments.
- binarySearchFinds the index of a given element in a sorted array using the binary search algorithm.
- bindCreates a function that invokes fn with a given context, optionally prepending any additional supplied parameters to the arguments.
- bindAllBinds methods of an object to the object itself, overwriting the existing method.
- bindKeyCreates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.
- binomialCoefficientCalculates the number of ways to choose k items from n items without repetition and without order.
- bothChecks if both of the given functions return true for a given set of arguments.
- bottomVisibleChecks if the bottom of the page is visible.
- btoaCreates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.
- bubbleSortSorts an array of numbers, using the bubble sort algorithm.
- bucketSortSorts an array of numbers, using the bucket sort algorithm.
- byteSizeReturns the length of a string in bytes.
- caesarCipherEncrypts or decrypts a given string using the Caesar cipher.
- callGiven a key and a set of arguments, call them when given a context.
- capitalizeCapitalizes the first letter of a string.
- capitalizeEveryWordCapitalizes the first letter of every word in a string.
- cartesianProductCalculates the cartesian product of two arrays.
- castArrayCasts the provided value as an array if it’s not one.
- celsiusToFahrenheitConverts Celsius to Fahrenheit.
- chainAsyncChains asynchronous functions.
- changeLightnessChanges the lightness value of an hsl() color string.
- checkPropCreates a function that will invoke a predicate function for the specified property on a given object.
- chunkChunks an array into smaller arrays of a specified size.
- chunkifyChunks an iterable into smaller arrays of a specified size.
- chunkIntoNChunks an array into n smaller arrays.
- clampNumberClamps num within the inclusive range specified by the boundary values a and b.
- cloneRegExpClones a regular expression.
- coalesceReturns the first defined, non-null argument.
- coalesceFactoryCustomizes a coalesce function that returns the first argument which is true based on the given validator.
- collectIntoChanges a function that accepts an array into a variadic function.
- colorizeAdds special characters to text to print in color in the console (combined with console.log()).
- combineCombines two arrays of objects, using the specified key to match objects.
- compactRemoves falsy values from an array.
- compactObjectDeeply removes all falsy values from an object or array.
- compactWhitespaceCompacts whitespaces in a string.
- complementReturns a function that is the logical complement of the given function, fn.
- composePerforms right-to-left function composition.
- composeRightPerforms left-to-right function composition.
- containsWhitespaceChecks if the given string contains any whitespace characters.
- convergeAccepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.
- copySignReturns the absolute value of the first number, but the sign of the second.
- copyToClipboardCopies a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener).
- countByGroups the elements of an array based on the given function and returns the count of elements in each group.
- counterCreates a counter with the specified range, step and duration for the specified selector.
- countOccurrencesCounts the occurrences of a value in an array.
- countSubstringsCounts the occurrences of a substring in a given string.
- countWeekDaysBetweenCounts the weekdays between two dates.
- createDirIfNotExistsCreates a directory, if it does not exist.
- createElementCreates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.
- createEventHubCreates a pub/sub (publish–subscribe) event hub with emit, on, and off methods.
- CSVToArrayConverts a comma-separated values (CSV) string to a 2D array.
- CSVToJSONConverts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.
- currentURLReturns the current URL.
- curryCurries a function.
- cycleGeneratorCreates a generator, looping over the given array indefinitely.
- dateRangeGeneratorCreates a generator, that generates all dates in the given range using the given step.
- dayNameGets the name of the weekday from a Date object.
- dayOfYearGets the day of the year (number in the range 1-366) from a Date object.
- daysAgoCalculates the date of n days ago from today as a string representation.
- daysFromNowCalculates the date of n days from today as a string representation.
- daysInMonthGets the number of days in the given month of the specified year.
- debounceCreates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.
- debouncePromiseCreates a debounced function that returns a promise, but delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked. All promises returned during this time will return the same data.
- decapitalizeDecapitalizes the first letter of a string.
- deepCloneCreates a deep clone of an object. Clones primitives, arrays and objects, excluding class instances.
- deepFlattenDeep flattens an array.
- deepFreezeDeep freezes an object.
- deepGetGets the target value in a nested JSON object, based on the keys array.
- deepMapKeysDeep maps an object’s keys.
- deepMergeDeeply merges two objects, using a function to handle keys present in both.
- defaultsAssigns default values for all properties in an object that are undefined.
- deferDefers invoking a function until the current call stack has cleared.
- degreesToRadsConverts an angle from degrees to radians.
- delayInvokes the provided function after ms milliseconds.
- detectDeviceTypeDetects whether the page is being viewed on a mobile device or a desktop.
- detectLanguageDetects the preferred language of the current user.
- differenceCalculates the difference between two arrays, without filtering duplicate values.
- differenceByReturns the difference between two arrays, after applying the provided function to each array element of both.
- differenceWithFilters out all values from an array for which the comparator function does not return true.
- digGets the target value in a nested JSON object, based on the given key.
- digitizeConverts a number to an array of digits, removing its sign if necessary.
- distanceCalculates the distance between two points.
- divmodReturns an array consisting of the quotient and remainder of the given numbers.
- dropCreates a new array with n elements removed from the left.
- dropRightCreates a new array with n elements removed from the right.
- dropRightWhileRemoves elements from the end of an array until the passed function returns true. Returns the remaining elements in the array.
- dropWhileRemoves elements in an array until the passed function returns true. Returns the remaining elements in the array.
- eitherChecks if at least one function returns true for a given set of arguments.
- elementContainsChecks if the parent element contains the child element.
- elementIsFocusedChecks if the given element is focused.
- elementIsVisibleInViewportChecks if the element specified is visible in the viewport.
- equalsPerforms a deep comparison between two values to determine if they are equivalent.
- escapeHTMLEscapes a string for use in HTML.
- escapeRegExpEscapes a string to use in a regular expression.
- euclideanDistanceCalculates the distance between two points in any number of dimensions.
- everyNthReturns every nth element in an array.
- expandTabsConvert tabs to spaces, where each tab corresponds to count spaces.
- extendHexExtends a 3-digit color code to a 6-digit color code.
- factorialCalculates the factorial of a number.
- fahrenheitToCelsiusConverts Fahrenheit to Celsius.
- fibonacciGenerates an array, containing the Fibonacci sequence, up until the nth term.
- filterNonUniqueCreates an array with the non-unique values filtered out.
- filterNonUniqueByCreates an array with the non-unique values filtered out, based on a provided comparator function.
- filterUniqueCreates an array with the unique values filtered out.
- filterUniqueByCreates an array with the unique values filtered out, based on a provided comparator function.
- findClosestAnchorFinds the anchor node closest to the given node, if any.
- findClosestMatchingNodeFinds the closest matching node starting at the given node.
- findFirstNFinds the first n elements for which the provided function returns a truthy value.
- findKeyFinds the first key that satisfies the provided testing function. Otherwise undefined is returned.
- findKeysFinds all the keys in the provided object that match the given value.
- findLastFinds the last element for which the provided function returns a truthy value.
- findLastIndexFinds the index of the last element for which the provided function returns a truthy value.
- findLastKeyFinds the last key that satisfies the provided testing function. Otherwise undefined is returned.
- findLastNFinds the last n elements for which the provided function returns a truthy value.
- flattenFlattens an array up to the specified depth.
- flattenObjectFlattens an object with the paths for keys.
- flipTakes a function as an argument, then makes the first argument the last.
- forEachRightExecutes a provided function once for each array element, starting from the array’s last element.
- formatDurationReturns the human-readable format of the given number of milliseconds.
- formatNumberFormats a number using the local number format order.
- formatSecondsReturns the ISO format of the given number of seconds.
- formToObjectEncodes a set of form elements as an object.
- forOwnIterates over all own properties of an object, running a callback for each one.
- forOwnRightIterates over all own properties of an object in reverse, running a callback for each one.
- frequenciesCreates an object with the unique values of an array as keys and their frequencies as the values.
- fromCamelCaseConverts a string from camelcase.
- fromTimestampCreates a Date object from a Unix timestamp.
- frozenSetCreates a frozen Set object.
- fullscreenOpens or closes an element in fullscreen mode.
- functionNameLogs the name of a function.
- functionsGets an array of function property names from own (and optionally inherited) enumerable properties of an object.
- gcdCalculates the greatest common divisor between two or more numbers/arrays.
- generateItemsGenerates an array with the given amount of items, using the given function.
- generatorToArrayConverts the output of a generator function to an array.
- geometricProgressionInitializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.
- getRetrieves a set of properties indicated by the given selectors from an object.
- getAncestorsReturns all the ancestors of an element from the document root to the given element.
- getBaseURLGets the current URL without any parameters or fragment identifiers.
- getColonTimeFromDateReturns a string of the form HH:MM:SS from a Date object.
- getDaysDiffBetweenDatesCalculates the difference (in days) between two dates.
- getElementsBiggerThanViewportReturns an array of HTML elements whose width is larger than that of the viewport’s.
- getHoursDiffBetweenDatesCalculates the difference (in hours) between two dates.
- getImagesFetches all images from within an element and puts them into an array.
- getMeridiemSuffixOfIntegerConverts an integer to a suffixed string, adding am or pm based on its value.
- getMinutesDiffBetweenDatesCalculates the difference (in minutes) between two dates.
- getMonthsDiffBetweenDatesCalculates the difference (in months) between two dates.
- getParentsUntilFinds all the ancestors of an element up until the element matched by the specified selector.
- getProtocolGets the protocol being used on the current page.
- getScrollPositionReturns the scroll position of the current page.
- getSecondsDiffBetweenDatesCalculates the difference (in seconds) between two dates.
- getSelectedTextGets the currently selected text.
- getSiblingsReturns an array containing all the siblings of the given element.
- getStyleRetrieves the value of a CSS rule for the specified element.
- getTimestampGets the Unix timestamp from a Date object.
- getTypeReturns the native type of a value.
- getURLParametersCreates an object containing the parameters of the current URL.
- getVerticalOffsetFinds the distance from a given element to the top of the document.
- groupByGroups the elements of an array based on the given function.
- hammingDistanceCalculates the Hamming distance between two values.
- hasClassChecks if the given element has the specified class.
- hasDuplicatesChecks if there are duplicate values in a flat array.
- hasFlagsChecks if the current process’s arguments contain the specified flags.
- hashBrowserCreates a hash for a value using the SHA-256 algorithm. Returns a promise.
- hashNodeCreates a hash for a value using the SHA-256 algorithm. Returns a promise.
- hasKeyChecks if the target value exists in a JSON object.
- hasManyChecks if an array has more than one value matching the given function.
- hasOneChecks if an array has only one value matching the given function.
- haveSameContentsChecks if two arrays contain the same elements regardless of order.
- headReturns the head of an array.
- heapsortSorts an array of numbers, using the heapsort algorithm.
- hexToRGBConverts a color code to an rgb() or rgba() string if alpha value is provided.
- hideHides all the elements specified.
- HSBToRGBConverts a HSB color tuple to RGB format.
- HSLToRGBConverts a HSL color tuple to RGB format.
- httpDeleteMakes a DELETE request to the passed URL.
- httpGetMakes a GET request to the passed URL.
- httpPostMakes a POST request to the passed URL.
- httpPutMakes a PUT request to the passed URL.
- httpsRedirectRedirects the page to HTTPS if it’s currently in HTTP.
- hzMeasures the number of times a function is executed per second (hz/hertz).
- includesAllChecks if all the elements in values are included in arr.
- includesAnyChecks if at least one element of values is included in arr.
- indentStringIndents each line in the provided string.
- indexByCreates an object from an array, using a function to map each value to a key.
- indexOfAllFinds all indexes of val in an array. If val never occurs, returns an empty array.
- indexOfSubstringsFinds all the indexes of a substring in a given string.
- indexOnCreates an object from an array, using the specified key and excluding it from each value.
- initialReturns all the elements of an array except the last one.
- initialize2DArrayInitializes a 2D array of given width and height and value.
- initializeArrayWithRangeInitializes an array containing the numbers in the specified range where start and end are inclusive with their common difference step.
- initializeArrayWithRangeRightInitializes an array containing the numbers in the specified range (in reverse) where start and end are inclusive with their common difference step.
- initializeArrayWithValuesInitializes and fills an array with the specified values.
- initializeNDArrayCreate a n-dimensional array with given value.
- injectCSSInjects the given CSS code into the current document
- inRangeChecks if the given number falls within the given range.
- insertAfterInserts an HTML string after the end of the specified element.
- insertAtMutates the original array to insert the given values after the specified index.
- insertBeforeInserts an HTML string before the start of the specified element.
- insertionSortSorts an array of numbers, using the insertion sort algorithm.
- intersectionReturns the elements that exist in both arrays, filtering duplicate values.
- intersectionByReturns the elements that exist in both arrays, after applying the provided function to each array element of both.
- intersectionWithReturns the elements that exist in both arrays, using a provided comparator function.
- invertKeyValuesInverts the key-value pairs of an object, without mutating it.
- isChecks if the provided value is of the specified type.
- isAbsoluteURLChecks if the given string is an absolute URL.
- isAfterDateChecks if a date is after another date.
- isAlphaChecks if a string contains only alpha characters.
- isAlphaNumericChecks if a string contains only alphanumeric characters.
- isAnagramChecks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
- isArrayLikeChecks if the provided argument is array-like (i.e. is iterable).
- isAsyncFunctionChecks if the given argument is an async function.
- isBeforeDateChecks if a date is before another date.
- isBetweenDatesChecks if a date is between two other dates.
- isBooleanChecks if the given argument is a native boolean element.
- isBrowserDetermines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
- isBrowserTabFocusedChecks if the browser tab of the page is focused.
- isContainedInChecks if the elements of the first array are contained in the second one regardless of order.
- isDateValidChecks if a valid date object can be created from the given values.
- isDeepFrozenChecks if an object is deeply frozen.
- isDisjointChecks if the two iterables are disjointed (have no common values).
- isDivisibleChecks if the first numeric argument is divisible by the second one.
- isDuplexStreamChecks if the given argument is a duplex (readable and writable) stream.
- isEmptyChecks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.
- isEvenChecks if the given number is even.
- isFunctionChecks if the given argument is a function.
- isGeneratorFunctionChecks if the given argument is a generator function.
- isISOStringChecks if the given string is valid in the simplified extended ISO format (ISO 8601).
- isLeapYearChecks if the given year is a leap year.
- isLocalStorageEnabledChecks if localStorage is enabled.
- isLowerCaseChecks if a string is lower case.
- isNegativeZeroChecks if the given value is equal to negative zero (-0).
- isNilChecks if the specified value is null or undefined.
- isNodeDetermines if the current runtime environment is Node.js.
- isNullChecks if the specified value is null.
- isNumberChecks if the given argument is a number.
- isObjectChecks if the passed value is an object or not.
- isObjectLikeChecks if a value is object-like.
- isOddChecks if the given number is odd.
- isPlainObjectChecks if the provided value is an object created by the Object constructor.
- isPowerOfTenChecks if the given number is a power of 10.
- isPowerOfTwoChecks if the given number is a power of 2.
- isPrimeChecks if the provided integer is a prime number.
- isPrimitiveChecks if the passed value is primitive or not.
- isPromiseLikeChecks if an object looks like a Promise.
- isReadableStreamChecks if the given argument is a readable stream.
- isSameDateChecks if a date is the same as another date.
- isSameOriginChecks if two URLs are on the same origin.
- isSessionStorageEnabledChecks if sessionStorage is enabled.
- isSortedChecks if a numeric array is sorted.
- isStreamChecks if the given argument is a stream.
- isStringChecks if the given argument is a string. Only works for string primitives.
- isSymbolChecks if the given argument is a symbol.
- isTravisCIChecks if the current environment is Travis CI.
- isUndefinedChecks if the specified value is undefined.
- isUpperCaseChecks if a string is upper case.
- isValidJSONChecks if the provided string is a valid JSON.
- isWeekdayChecks if the given date is a weekday.
- isWeekendChecks if the given date is a weekend.
- isWritableStreamChecks if the given argument is a writable stream.
- joinJoins all elements of an array into a string and returns this string. Uses a separator and an end separator.
- JSONtoCSVConverts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.
- JSONToFileWrites a JSON object to a file.
- juxtTakes several functions as argument and returns a function that is the juxtaposition of those functions.
- kMeansGroups the given data into k clusters, using the k-means clustering algorithm.
- kmToMilesConverts kilometers to miles.
- kNearestNeighborsClassifies a data point relative to a labelled data set, using the k-nearest neighbors algorithm.
- lastReturns the last element in an array.
- lastDateOfMonthReturns the string representation of the last date in the given date’s month.
- lcmCalculates the least common multiple of two or more numbers.
- levenshteinDistanceCalculates the difference between two strings, using the Levenshtein distance algorithm.
- linearSearchFinds the first index of a given element in an array using the linear search algorithm.
- listenOnceAdds an event listener to an element that will only run the callback the first time the event is triggered.
- logBaseCalculates the logarithm of the given number in the given base.
- longestItemTakes any number of iterable objects or objects with a length property and returns the longest one.
- lowercaseKeysCreates a new object from the specified object, where all the keys are in lowercase.
- luhnCheckImplementation of the Luhn Algorithm used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
- mapConsecutiveMaps each block of n consencutive elements using the given function, fn.
- mapKeysMaps the keys of an object using the provided function, generating a new object.
- mapNumRangeMaps a number from one range to another range.
- mapObjectMaps the values of an array to an object using a function.
- mapStringCreates a new string with the results of calling a provided function on every character in the given string.
- mapValuesMaps the values of an object using the provided function, generating a new object with the same keys.
- maskReplaces all but the last num of characters with the specified mask character.
- matchesCompares two objects to determine if the first one contains equivalent property values to the second one.
- matchesWithCompares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
- maxByReturns the maximum value of an array, after mapping each element to a value using the provided function.
- maxDateReturns the maximum of the given dates.
- maxNReturns the n maximum elements from the provided array.
- medianCalculates the median of an array of numbers.
- memoizeReturns the memoized (cached) function.
- mergeCreates a new object from the combination of two or more objects.
- mergeSortSorts an array of numbers, using the merge sort algorithm.
- mergeSortedArraysMerges two sorted arrays into one.
- midpointCalculates the midpoint between two pairs of (x,y) points.
- milesToKmConverts miles to kilometers.
- minByReturns the minimum value of an array, after mapping each element to a value using the provided function.
- minDateReturns the minimum of the given dates.
- minNReturns the n minimum elements from the provided array.
- mostFrequentReturns the most frequent element in an array.
- mostPerformantReturns the index of the function in an array of functions which executed the fastest.
- negateNegates a predicate function.
- nestNests recursively objects linked to one another in a flat array.
- nodeListToArrayConverts a NodeList to an array.
- noneChecks if the provided predicate function returns false for all elements in a collection.
- norChecks if none of the arguments are true.
- normalizeLineEndingsNormalizes line endings in a string.
- notReturns the logical inverse of the given value.
- nthArgCreates a function that gets the argument at index n.
- nthElementReturns the nth element of an array.
- nthRootCalculates the nth root of a given number.
- objectFromPairsCreates an object from the given key-value pairs.
- objectToEntriesCreates an array of key-value pair arrays from an object.
- objectToPairsCreates an array of key-value pair arrays from an object.
- objectToQueryStringGenerates a query string from the key-value pairs of the given object.
- observeMutationsCreates a new MutationObserver and runs the provided callback for each mutation on the specified element.
- offRemoves an event listener from an element.
- offsetMoves the specified amount of elements to the end of the array.
- omitOmits the key-value pairs corresponding to the given keys from an object.
- omitByOmits the key-value pairs corresponding to the keys of the object for which the given function returns falsy.
- onAdds an event listener to an element with the ability to use event delegation.
- onceEnsures a function is called only once.
- onClickOutsideRuns the callback whenever the user clicks outside of the specified element.
- onScrollStopRuns the callback whenever the user has stopped scrolling.
- onUserInputChangeRuns the callback whenever the user input type changes (mouse or touch).
- orChecks if at least one of the arguments is true.
- orderBySorts an array of objects, ordered by properties and orders.
- orderWithSorts an array of objects, ordered by a property, based on the array of orders provided.
- overCreates a function that invokes each provided function with the arguments it receives and returns the results.
- overArgsCreates a function that invokes the provided function with its arguments transformed.
- padPads a string on both sides with the specified character, if it’s shorter than the specified length.
- padNumberPads a given number to the specified length.
- palindromeChecks if the given string is a palindrome.
- parseCookieParses an HTTP Cookie header string, returning an object of all cookie name-value pairs.
- partialCreates a function that invokes fn with partials prepended to the arguments it receives.
- partialRightCreates a function that invokes fn with partials appended to the arguments it receives.
- partitionGroups the elements into two arrays, depending on the provided function’s truthiness for each element.
- partitionByApplies fn to each value in arr, splitting it each time the provided function returns a new value.
- percentileCalculates the percentage of numbers in the given array that are less or equal to the given value.
- permutationsGenerates all permutations of an array’s elements (contains duplicates).
- pickPicks the key-value pairs corresponding to the given keys from an object.
- pickByCreates an object composed of the properties the given function returns truthy for.
- pipeAsyncFunctionsPerforms left-to-right function composition for asynchronous functions.
- pipeFunctionsPerforms left-to-right function composition.
- pluckConverts an array of objects into an array of values corresponding to the specified key.
- pluralizeReturns the singular or plural form of the word based on the input number, using an optional dictionary if supplied.
- powersetReturns the powerset of a given array of numbers.
- prefersDarkColorSchemeChecks if the user color scheme preference is dark.
- prefersLightColorSchemeChecks if the user color scheme preference is light.
- prefixPrefixes a CSS property based on the current browser.
- prettyBytesConverts a number in bytes to a human-readable string.
- primeFactorsFinds the prime factors of a given number using the trial division algorithm.
- primesGenerates primes up to a given number, using the Sieve of Eratosthenes.
- prodCalculates the product of two or more numbers/arrays.
- promisifyConverts an asynchronous function to return a promise.
- pullMutates the original array to filter out the values specified.
- pullAtIndexMutates the original array to filter out the values at the specified indexes. Returns the removed elements.
- pullAtValueMutates the original array to filter out the values specified. Returns the removed elements.
- pullByMutates the original array to filter out the values specified, based on a given iterator function.
- quarterOfYearReturns the quarter and year to which the supplied date belongs to.
- queryStringToObjectGenerates an object from the given query string or URL.
- quickSortSorts an array of numbers, using the quicksort algorithm.
- radsToDegreesConverts an angle from radians to degrees.
- randomAlphaNumericGenerates a random string with the specified length.
- randomBooleanGenerates a random boolean value.
- randomHexColorCodeGenerates a random hexadecimal color code.
- randomIntArrayInRangeGenerates an array of n random integers in the specified range.
- randomIntegerInRangeGenerates a random integer in the specified range.
- randomNumberInRangeGenerates a random number in the specified range.
- rangeGeneratorCreates a generator, that generates all values in the given range using the given step.
- readFileLinesReturns an array of lines from the specified file.
- reargCreates a function that invokes the provided function with its arguments arranged according to the specified indexes.
- recordAnimationFramesInvokes the provided callback on each animation frame.
- redirectRedirects to a specified URL.
- reducedFilterFilters an array of objects based on a condition while also filtering out unspecified keys.
- reduceSuccessiveApplies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.
- reduceWhichReturns the minimum/maximum value of an array, after applying the provided function to set the comparing rule.
- rejectFilters an array’s values based on a predicate function, returning only values for which the predicate function returns false.
- removeMutates an array by removing elements for which the given function returns false.
- removeAccentsRemoves accents from strings.
- removeClassRemoves a class from an HTML element.
- removeElementRemoves an element from the DOM.
- removeEventListenerAllDetaches an event listener from all the provided targets.
- removeNonASCIIRemoves non-printable ASCII characters.
- removeWhitespaceReturns a string with whitespaces removed.
- renameKeysReplaces the names of multiple object keys with the values provided.
- renderElementRenders the given DOM tree in the specified DOM element.
- repeatGeneratorCreates a generator, repeating the given value indefinitely.
- replaceLastReplaces the last occurence of a pattern in a string.
- requireUncachedLoads a module after removing it from the cache (if exists).
- reverseNumberReverses a number.
- reverseStringReverses a string.
- RGBToHexConverts the values of RGB components to a hexadecimal color code.
- RGBToHSBConverts a RGB color tuple to HSB format.
- RGBToHSLConverts a RGB color tuple to HSL format.
- roundRounds a number to a specified amount of digits.
- runAsyncRuns a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.
- runPromisesInSeriesRuns an array of promises in series.
- sampleGets a random element from an array.
- sampleSizeGets n random elements at unique keys from an array up to the size of the array.
- scrollToTopSmooth-scrolls to the top of the page.
- sdbmHashes the input string into a whole number.
- selectionSortSorts an array of numbers, using the selection sort algorithm.
- serializeCookieSerializes a cookie name-value pair into a Set-Cookie header string.
- serializeFormEncodes a set of form elements as a query string.
- setStyleSets the value of a CSS rule for the specified HTML element.
- shallowCloneCreates a shallow clone of an object.
- shankHas the same functionality as Array.prototype.splice(), but returning a new array instead of mutating the original array.
- showShows all the elements specified.
- shuffleRandomizes the order of the values of an array, returning a new array.
- similarityReturns an array of elements that appear in both arrays.
- sizeGets the size of an array, object or string.
- sleepDelays the execution of an asynchronous function.
- slugifyConverts a string to a URL-friendly slug.
- smoothScrollSmoothly scrolls the element on which it’s called into the visible area of the browser window.
- sortCharactersInStringAlphabetically sorts the characters in a string.
- sortedIndexFinds the lowest index at which a value should be inserted into an array in order to maintain its sorting order.
- sortedIndexByFinds the lowest index at which a value should be inserted into an array in order to maintain its sorting order, based on the provided iterator function.
- sortedLastIndexFinds the highest index at which a value should be inserted into an array in order to maintain its sort order.
- sortedLastIndexByFinds the highest index at which a value should be inserted into an array in order to maintain its sort order, based on a provided iterator function.
- splitLinesSplits a multiline string into an array of lines.
- spreadOverTakes a variadic function and returns a function that accepts an array of arguments.
- stableSortPerforms stable sorting of an array, preserving the initial indexes of items when their values are the same.
- standardDeviationCalculates the standard deviation of an array of numbers.
- stringifyCircularJSONSerializes a JSON object containing circular references into a JSON format.
- stringPermutationsGenerates all permutations of a string (contains duplicates).
- stripHTMLTagsRemoves HTML/XML tags from string.
- subSetChecks if the first iterable is a subset of the second one, excluding duplicate values.
- sumCalculates the sum of two or more numbers/arrays.
- sumByCalculates the sum of an array, after mapping each element to a value using the provided function.
- sumNSums all the numbers between 1 and n.
- sumPowerCalculates the sum of the powers of all the numbers from start to end (both inclusive).
- superSetChecks if the first iterable is a superset of the second one, excluding duplicate values.
- supportsTouchEventsChecks if touch events are supported.
- swapCaseCreates a string with uppercase characters converted to lowercase and vice versa.
- symbolizeKeysCreates a new object, converting each key to a Symbol.
- symmetricDifferenceReturns the symmetric difference between two arrays, without filtering out duplicate values.
- symmetricDifferenceByReturns the symmetric difference between two arrays, after applying the provided function to each array element of both.
- symmetricDifferenceWithReturns the symmetric difference between two arrays, using a provided function as a comparator.
- tailReturns all elements in an array except for the first one.
- takeCreates an array with n elements removed from the beginning.
- takeRightCreates an array with n elements removed from the end.
- takeRightUntilRemoves elements from the end of an array until the passed function returns true. Returns the removed elements.
- takeRightWhileRemoves elements from the end of an array until the passed function returns false. Returns the removed elements.
- takeUntilRemoves elements in an array until the passed function returns true. Returns the removed elements.
- takeWhileRemoves elements in an array until the passed function returns false. Returns the removed elements.
- throttleCreates a throttled function that only invokes the provided function at most once per every wait milliseconds
- timesIterates over a callback n times
- timeTakenMeasures the time it takes for a function to execute.
- toCamelCaseConverts a string to camelcase.
- toCharArrayConverts a string to an array of characters.
- toCurrencyTakes a number and returns it in the specified currency formatting.
- toDecimalMarkConverts a number to a decimal mark formatted string.
- toggleClassToggles a class for an HTML element.
- toHashReduces a given array-like into a value hash (keyed data store).
- toHSLArrayConverts an hsl() color string to an array of values.
- toHSLObjectConverts an hsl() color string to an object with the values of each color.
- toISOStringWithTimezoneConverts a date to extended ISO format (ISO 8601), including timezone offset.
- toKebabCaseConverts a string to kebab case.
- tomorrowResults in a string representation of tomorrow’s date.
- toOrdinalSuffixTakes a number and returns it as a string with the correct ordinal indicator suffix.
- toPairsCreates an array of key-value pair arrays from an object or other iterable.
- toRGBArrayConverts an rgb() color string to an array of values.
- toRGBObjectConverts an rgb() color string to an object with the values of each color.
- toRomanNumeralConverts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).
- toSafeIntegerConverts a value to a safe integer.
- toSnakeCaseConverts a string to snake case.
- toTitleCaseConverts a string to title case.
- transformApplies a function against an accumulator and each key in the object (from left to right).
- triggerEventTriggers a specific event on a given element, optionally passing custom data.
- truncateStringTruncates a string up to a specified length.
- truncateStringAtWhitespaceTruncates a string up to specified length, respecting whitespace when possible.
- truthCheckCollectionChecks if the predicate function is truthy for all elements of a collection.
- unaryCreates a function that accepts up to one argument, ignoring any additional arguments.
- uncurryUncurries a function up to depth n.
- unescapeHTMLUnescapes escaped HTML characters.
- unflattenObjectUnflatten an object with the paths for keys.
- unfoldBuilds an array, using an iterator function and an initial seed value.
- unionReturns every element that exists in any of the two arrays at least once.
- unionByReturns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.
- unionWithReturns every element that exists in any of the two arrays at least once, using a provided comparator function.
- uniqueElementsFinds all unique values in an array.
- uniqueElementsByFinds all unique values of an array, based on a provided comparator function.
- uniqueElementsByRightFinds all unique values of an array, based on a provided comparator function, starting from the right.
- uniqueSymmetricDifferenceReturns the unique symmetric difference between two arrays, not containing duplicate values from either array.
- untildifyConverts a tilde path to an absolute path.
- unzipCreates an array of arrays, ungrouping the elements in an array produced by zip.
- unzipWithCreates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.
- URLJoinJoins all given URL segments together, then normalizes the resulting URL.
- UUIDGeneratorBrowserGenerates a UUID in a browser.
- UUIDGeneratorNodeGenerates a UUID in Node.JS.
- validateNumberChecks if the given value is a number.
- vectorAngleCalculates the angle (theta) between two vectors.
- vectorDistanceCalculates the distance between two vectors.
- walkThroughCreates a generator, that walks through all the keys of a given object.
- weekOfYearReturns the zero-indexed week of the year that a date corresponds to.
- weightedAverageCalculates the weighted average of two or more numbers.
- weightedSampleGets a random element from an array, using the provided weights as the probabilities for each element.
- whenReturns a function that takes one argument and runs a callback if it’s truthy or returns it if falsy.
- withoutFilters out the elements of an array that have one of the specified values.
- wordsConverts a given string into an array of words.
- wordWrapWraps a string to a given number of characters using a string break character.
- xorChecks if only one of the arguments is true.
- xProdCreates a new array out of the two supplied by creating each possible pair from the arrays.
- yesNoReturns true if the string is y/yes or false if the string is n/no.
- yesterdayResults in a string representation of yesterday’s date.
- zipCreates an array of elements, grouped based on their position in the original arrays.
- zipObjectAssociates properties to values, given array of valid property identifiers and an array of values.
- zipWithCreates an array of elements, grouped based on the position in the original arrays and using a function to specify how grouped values should be combined.
No snippet matches that filter.