30-seconds-of-code
Version:
A collection of useful JavaScript snippets.
1,977 lines (1,418 loc) ⢠234 kB
Markdown

# 30 seconds of code
[](https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://www.npmjs.com/package/30-seconds-of-code) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.com/30-seconds/30-seconds-of-code) [](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=30-seconds/30-seconds-of-code&utm_campaign=Badge_Grade) [](https://codeclimate.com/github/30-seconds/30-seconds-of-code/maintainability) [](https://github.com/Flet/semistandard) [](https://snyk.io/test/github/30-seconds/30-seconds-of-code?targetFile=package.json) [](https://www.producthunt.com/posts/30-seconds-of-code)
> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
[](https://www.digitalocean.com)
- Use <kbd>Ctrl</kbd> + <kbd>F</kbd> or <kbd>command</kbd> + <kbd>F</kbd> to search for a snippet.
- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md).
- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility.
- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets).
- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets).
#### Related
- [30 Seconds of CSS](https://atomiks.github.io/30-seconds-of-css/)
- [30 Seconds of Interviews](https://30secondsofinterviews.org/)
- [30 Seconds of Python](https://github.com/kriadmin/30-seconds-of-python-code)
#### Package
ā ļø **NOTICE:** A few of our snippets are not yet optimized for production (see disclaimers for individual snippet issues).
You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code).
```bash
# With npm
npm install 30-seconds-of-code
# With yarn
yarn add 30-seconds-of-code
```
CDN links
- [ES2017 Full (UMD)](https://unpkg.com/30-seconds-of-code)
- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js)
<details>
<summary>Details</summary>
**Browser**
> IMPORTANT: replace the `src` with the full version link and desired target spec (such as ES5 minified)):
```html
<script src="https://unpkg.com/30-seconds-of-code"></script>
<script>
_30s.average(1, 2, 3);
</script>
```
**Node**
```js
// CommonJS
const _30s = require('30-seconds-of-code');
_30s.average(1, 2, 3);
// ES Modules
import _30s from '30-seconds-of-code';
_30s.average(1, 2, 3);
```
To import snippets directly:
```js
// CommonJS
const { average } = require('30-seconds-of-code');
average(1, 2, 3);
// ES Modules
import { average } from '30-seconds-of-code';
average(1, 2, 3);
```
</details>
## Table of Contents
### š Adapter
<details>
<summary>View contents</summary>
* [`ary`](#ary)
* [`call`](#call)
* [`collectInto`](#collectinto)
* [`flip`](#flip)
* [`over`](#over)
* [`overArgs`](#overargs)
* [`pipeAsyncFunctions`](#pipeasyncfunctions)
* [`pipeFunctions`](#pipefunctions)
* [`promisify`](#promisify)
* [`rearg`](#rearg)
* [`spreadOver`](#spreadover)
* [`unary`](#unary)
</details>
### š Array
<details>
<summary>View contents</summary>
* [`all`](#all)
* [`allEqual`](#allequal)
* [`any`](#any)
* [`arrayToCSV`](#arraytocsv)
* [`bifurcate`](#bifurcate)
* [`bifurcateBy`](#bifurcateby)
* [`chunk`](#chunk)
* [`compact`](#compact)
* [`countBy`](#countby)
* [`countOccurrences`](#countoccurrences)
* [`deepFlatten`](#deepflatten)
* [`difference`](#difference)
* [`differenceBy`](#differenceby)
* [`differenceWith`](#differencewith)
* [`drop`](#drop)
* [`dropRight`](#dropright)
* [`dropRightWhile`](#droprightwhile)
* [`dropWhile`](#dropwhile)
* [`everyNth`](#everynth)
* [`filterNonUnique`](#filternonunique)
* [`filterNonUniqueBy`](#filternonuniqueby)
* [`findLast`](#findlast)
* [`findLastIndex`](#findlastindex)
* [`flatten`](#flatten)
* [`forEachRight`](#foreachright)
* [`groupBy`](#groupby)
* [`head`](#head)
* [`indexOfAll`](#indexofall)
* [`initial`](#initial)
* [`initialize2DArray`](#initialize2darray)
* [`initializeArrayWithRange`](#initializearraywithrange)
* [`initializeArrayWithRangeRight`](#initializearraywithrangeright)
* [`initializeArrayWithValues`](#initializearraywithvalues)
* [`initializeNDArray`](#initializendarray)
* [`intersection`](#intersection)
* [`intersectionBy`](#intersectionby)
* [`intersectionWith`](#intersectionwith)
* [`isSorted`](#issorted)
* [`join`](#join)
* [`JSONtoCSV`](#jsontocsv-)
* [`last`](#last)
* [`longestItem`](#longestitem)
* [`mapObject`](#mapobject-)
* [`maxN`](#maxn)
* [`minN`](#minn)
* [`none`](#none)
* [`nthElement`](#nthelement)
* [`offset`](#offset)
* [`partition`](#partition)
* [`permutations`](#permutations-)
* [`pull`](#pull)
* [`pullAtIndex`](#pullatindex-)
* [`pullAtValue`](#pullatvalue-)
* [`pullBy`](#pullby-)
* [`reducedFilter`](#reducedfilter)
* [`reduceSuccessive`](#reducesuccessive)
* [`reduceWhich`](#reducewhich)
* [`reject`](#reject)
* [`remove`](#remove)
* [`sample`](#sample)
* [`sampleSize`](#samplesize)
* [`shuffle`](#shuffle)
* [`similarity`](#similarity)
* [`sortedIndex`](#sortedindex)
* [`sortedIndexBy`](#sortedindexby)
* [`sortedLastIndex`](#sortedlastindex)
* [`sortedLastIndexBy`](#sortedlastindexby)
* [`stableSort`](#stablesort-)
* [`symmetricDifference`](#symmetricdifference)
* [`symmetricDifferenceBy`](#symmetricdifferenceby)
* [`symmetricDifferenceWith`](#symmetricdifferencewith)
* [`tail`](#tail)
* [`take`](#take)
* [`takeRight`](#takeright)
* [`takeRightWhile`](#takerightwhile)
* [`takeWhile`](#takewhile)
* [`toHash`](#tohash)
* [`union`](#union)
* [`unionBy`](#unionby)
* [`unionWith`](#unionwith)
* [`uniqueElements`](#uniqueelements)
* [`uniqueElementsBy`](#uniqueelementsby)
* [`uniqueElementsByRight`](#uniqueelementsbyright)
* [`uniqueSymmetricDifference`](#uniquesymmetricdifference)
* [`unzip`](#unzip)
* [`unzipWith`](#unzipwith-)
* [`without`](#without)
* [`xProd`](#xprod)
* [`zip`](#zip)
* [`zipObject`](#zipobject)
* [`zipWith`](#zipwith-)
</details>
### š Browser
<details>
<summary>View contents</summary>
* [`arrayToHtmlList`](#arraytohtmllist)
* [`bottomVisible`](#bottomvisible)
* [`copyToClipboard`](#copytoclipboard-)
* [`counter`](#counter-)
* [`createElement`](#createelement)
* [`createEventHub`](#createeventhub-)
* [`currentURL`](#currenturl)
* [`detectDeviceType`](#detectdevicetype)
* [`elementContains`](#elementcontains)
* [`elementIsVisibleInViewport`](#elementisvisibleinviewport-)
* [`getScrollPosition`](#getscrollposition)
* [`getStyle`](#getstyle)
* [`hasClass`](#hasclass)
* [`hashBrowser`](#hashbrowser-)
* [`hide`](#hide)
* [`httpsRedirect`](#httpsredirect)
* [`insertAfter`](#insertafter)
* [`insertBefore`](#insertbefore)
* [`isBrowserTabFocused`](#isbrowsertabfocused)
* [`nodeListToArray`](#nodelisttoarray)
* [`observeMutations`](#observemutations-)
* [`off`](#off)
* [`on`](#on)
* [`onUserInputChange`](#onuserinputchange-)
* [`prefix`](#prefix)
* [`recordAnimationFrames`](#recordanimationframes)
* [`redirect`](#redirect)
* [`runAsync`](#runasync-)
* [`scrollToTop`](#scrolltotop)
* [`setStyle`](#setstyle)
* [`show`](#show)
* [`smoothScroll`](#smoothscroll)
* [`toggleClass`](#toggleclass)
* [`triggerEvent`](#triggerevent)
* [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser)
</details>
### ā±ļø Date
<details>
<summary>View contents</summary>
* [`formatDuration`](#formatduration)
* [`getColonTimeFromDate`](#getcolontimefromdate)
* [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates)
* [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger)
* [`tomorrow`](#tomorrow)
</details>
### šļø Function
<details>
<summary>View contents</summary>
* [`attempt`](#attempt)
* [`bind`](#bind)
* [`bindKey`](#bindkey)
* [`chainAsync`](#chainasync)
* [`compose`](#compose)
* [`composeRight`](#composeright)
* [`converge`](#converge)
* [`curry`](#curry)
* [`debounce`](#debounce)
* [`defer`](#defer)
* [`delay`](#delay)
* [`functionName`](#functionname)
* [`hz`](#hz)
* [`memoize`](#memoize-)
* [`negate`](#negate)
* [`once`](#once)
* [`partial`](#partial)
* [`partialRight`](#partialright)
* [`runPromisesInSeries`](#runpromisesinseries)
* [`sleep`](#sleep)
* [`throttle`](#throttle-)
* [`times`](#times)
* [`uncurry`](#uncurry)
* [`unfold`](#unfold)
* [`when`](#when)
</details>
### ā Math
<details>
<summary>View contents</summary>
* [`approximatelyEqual`](#approximatelyequal)
* [`average`](#average)
* [`averageBy`](#averageby)
* [`binomialCoefficient`](#binomialcoefficient)
* [`clampNumber`](#clampnumber)
* [`degreesToRads`](#degreestorads)
* [`digitize`](#digitize)
* [`distance`](#distance)
* [`elo`](#elo-)
* [`factorial`](#factorial)
* [`fibonacci`](#fibonacci)
* [`gcd`](#gcd)
* [`geometricProgression`](#geometricprogression)
* [`hammingDistance`](#hammingdistance)
* [`inRange`](#inrange)
* [`isDivisible`](#isdivisible)
* [`isEven`](#iseven)
* [`isPrime`](#isprime)
* [`lcm`](#lcm)
* [`luhnCheck`](#luhncheck-)
* [`maxBy`](#maxby)
* [`median`](#median)
* [`minBy`](#minby)
* [`percentile`](#percentile)
* [`powerset`](#powerset)
* [`primes`](#primes)
* [`radsToDegrees`](#radstodegrees)
* [`randomIntArrayInRange`](#randomintarrayinrange)
* [`randomIntegerInRange`](#randomintegerinrange)
* [`randomNumberInRange`](#randomnumberinrange)
* [`round`](#round)
* [`sdbm`](#sdbm)
* [`standardDeviation`](#standarddeviation)
* [`sum`](#sum)
* [`sumBy`](#sumby)
* [`sumPower`](#sumpower)
* [`toSafeInteger`](#tosafeinteger)
</details>
### š¦ Node
<details>
<summary>View contents</summary>
* [`atob`](#atob)
* [`btoa`](#btoa)
* [`colorize`](#colorize)
* [`hasFlags`](#hasflags)
* [`hashNode`](#hashnode)
* [`isTravisCI`](#istravisci)
* [`JSONToFile`](#jsontofile)
* [`readFileLines`](#readfilelines)
* [`untildify`](#untildify)
* [`UUIDGeneratorNode`](#uuidgeneratornode)
</details>
### šļø Object
<details>
<summary>View contents</summary>
* [`bindAll`](#bindall)
* [`deepClone`](#deepclone)
* [`deepFreeze`](#deepfreeze)
* [`defaults`](#defaults)
* [`dig`](#dig)
* [`equals`](#equals-)
* [`findKey`](#findkey)
* [`findLastKey`](#findlastkey)
* [`flattenObject`](#flattenobject)
* [`forOwn`](#forown)
* [`forOwnRight`](#forownright)
* [`functions`](#functions)
* [`get`](#get)
* [`invertKeyValues`](#invertkeyvalues)
* [`lowercaseKeys`](#lowercasekeys)
* [`mapKeys`](#mapkeys)
* [`mapValues`](#mapvalues)
* [`matches`](#matches)
* [`matchesWith`](#matcheswith)
* [`merge`](#merge)
* [`nest`](#nest)
* [`objectFromPairs`](#objectfrompairs)
* [`objectToPairs`](#objecttopairs)
* [`omit`](#omit)
* [`omitBy`](#omitby)
* [`orderBy`](#orderby)
* [`pick`](#pick)
* [`pickBy`](#pickby)
* [`renameKeys`](#renamekeys)
* [`shallowClone`](#shallowclone)
* [`size`](#size)
* [`transform`](#transform)
* [`truthCheckCollection`](#truthcheckcollection)
* [`unflattenObject`](#unflattenobject-)
</details>
### š String
<details>
<summary>View contents</summary>
* [`byteSize`](#bytesize)
* [`capitalize`](#capitalize)
* [`capitalizeEveryWord`](#capitalizeeveryword)
* [`CSVToArray`](#csvtoarray)
* [`CSVToJSON`](#csvtojson-)
* [`decapitalize`](#decapitalize)
* [`escapeHTML`](#escapehtml)
* [`escapeRegExp`](#escaperegexp)
* [`fromCamelCase`](#fromcamelcase)
* [`isAbsoluteURL`](#isabsoluteurl)
* [`isAnagram`](#isanagram)
* [`isLowerCase`](#islowercase)
* [`isUpperCase`](#isuppercase)
* [`mapString`](#mapstring)
* [`mask`](#mask)
* [`pad`](#pad)
* [`palindrome`](#palindrome)
* [`pluralize`](#pluralize)
* [`removeNonASCII`](#removenonascii)
* [`reverseString`](#reversestring)
* [`sortCharactersInString`](#sortcharactersinstring)
* [`splitLines`](#splitlines)
* [`stringPermutations`](#stringpermutations-)
* [`stripHTMLTags`](#striphtmltags)
* [`toCamelCase`](#tocamelcase)
* [`toKebabCase`](#tokebabcase)
* [`toSnakeCase`](#tosnakecase)
* [`truncateString`](#truncatestring)
* [`unescapeHTML`](#unescapehtml)
* [`URLJoin`](#urljoin-)
* [`words`](#words)
</details>
### š Type
<details>
<summary>View contents</summary>
* [`getType`](#gettype)
* [`is`](#is)
* [`isArrayLike`](#isarraylike)
* [`isBoolean`](#isboolean)
* [`isEmpty`](#isempty)
* [`isFunction`](#isfunction)
* [`isNil`](#isnil)
* [`isNull`](#isnull)
* [`isNumber`](#isnumber)
* [`isObject`](#isobject)
* [`isObjectLike`](#isobjectlike)
* [`isPlainObject`](#isplainobject)
* [`isPrimitive`](#isprimitive)
* [`isPromiseLike`](#ispromiselike)
* [`isString`](#isstring)
* [`isSymbol`](#issymbol)
* [`isUndefined`](#isundefined)
* [`isValidJSON`](#isvalidjson)
</details>
### š§ Utility
<details>
<summary>View contents</summary>
* [`castArray`](#castarray)
* [`cloneRegExp`](#cloneregexp)
* [`coalesce`](#coalesce)
* [`coalesceFactory`](#coalescefactory)
* [`extendHex`](#extendhex)
* [`getURLParameters`](#geturlparameters)
* [`hexToRGB`](#hextorgb-)
* [`httpGet`](#httpget)
* [`httpPost`](#httppost)
* [`isBrowser`](#isbrowser)
* [`mostPerformant`](#mostperformant)
* [`nthArg`](#ntharg)
* [`parseCookie`](#parsecookie)
* [`prettyBytes`](#prettybytes-)
* [`randomHexColorCode`](#randomhexcolorcode)
* [`RGBToHex`](#rgbtohex)
* [`serializeCookie`](#serializecookie)
* [`timeTaken`](#timetaken)
* [`toCurrency`](#tocurrency)
* [`toDecimalMark`](#todecimalmark)
* [`toOrdinalSuffix`](#toordinalsuffix)
* [`validateNumber`](#validatenumber)
* [`yesNo`](#yesno)
</details>
---
## š Adapter
### ary
Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`).
```js
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
```
<details>
<summary>Examples</summary>
```js
const firstTwoMax = ary(Math.max, 2);
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
```js
const call = (key, ...args) => context => context[key](...args);
```
<details>
<summary>Examples</summary>
```js
Promise.resolve([1, 2, 3])
.then(call('map', x => 2 * x))
.then(console.log); //[ 2, 4, 6 ]
const map = call.bind(null, 'map');
Promise.resolve([1, 2, 3])
.then(map(x => 2 * x))
.then(console.log); //[ 2, 4, 6 ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### collectInto
Changes a function that accepts an array into a variadic function.
Given a function, return a closure that collects all inputs into an array-accepting function.
```js
const collectInto = fn => (...args) => fn(args);
```
<details>
<summary>Examples</summary>
```js
const Pall = collectInto(Promise.all.bind(Promise));
let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
```
</details>
<br>[⬠Back to top](#table-of-contents)
### flip
Flip takes a function as an argument, then makes the first argument the last.
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
```js
const flip = fn => (first, ...rest) => fn(...rest, first);
```
<details>
<summary>Examples</summary>
```js
let a = { name: 'John Smith' };
let b = {};
const mergeFrom = flip(Object.assign);
let mergePerson = mergeFrom.bind(null, a);
mergePerson(b); // == b
b = {};
Object.assign(b, a); // == b
```
</details>
<br>[⬠Back to top](#table-of-contents)
### over
Creates a function that invokes each provided function with the arguments it receives and returns the results.
Use `Array.map()` and `Function.apply()` to apply each function to the given arguments.
```js
const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
```
<details>
<summary>Examples</summary>
```js
const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1,5]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### overArgs
Creates a function that invokes the provided function with its arguments transformed.
Use `Array.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
```js
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
```
<details>
<summary>Examples</summary>
```js
const square = n => n * n;
const double = n => n * 2;
const fn = overArgs((x, y) => [x, y], [square, double]);
fn(9, 3); // [81, 6]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### pipeAsyncFunctions
Performs left-to-right function composition for asynchronous functions.
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`.
The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`.
All functions must be unary.
```js
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
```
<details>
<summary>Examples</summary>
```js
const sum = pipeAsyncFunctions(
x => x + 1,
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
x => x + 3,
async x => (await x) + 4
);
(async () => {
console.log(await sum(5)); // 15 (after one second)
})();
```
</details>
<br>[⬠Back to top](#table-of-contents)
### pipeFunctions
Performs left-to-right function composition.
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
```js
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
```
<details>
<summary>Examples</summary>
```js
const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15
```
</details>
<br>[⬠Back to top](#table-of-contents)
### promisify
Converts an asynchronous function to return a promise.
Use currying to return a function returning a `Promise` that calls the original function.
Use the `...rest` operator to pass in all the parameters.
*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
```js
const promisify = func => (...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) => (err ? reject(err) : resolve(result)))
);
```
<details>
<summary>Examples</summary>
```js
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
```
</details>
<br>[⬠Back to top](#table-of-contents)
### rearg
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
Use `Array.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
```js
const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
```
<details>
<summary>Examples</summary>
```js
var rearged = rearg(
function(a, b, c) {
return [a, b, c];
},
[2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']
```
</details>
<br>[⬠Back to top](#table-of-contents)
### spreadOver
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
```js
const spreadOver = fn => argsArr => fn(...argsArr);
```
<details>
<summary>Examples</summary>
```js
const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // 3
```
</details>
<br>[⬠Back to top](#table-of-contents)
### unary
Creates a function that accepts up to one argument, ignoring any additional arguments.
Call the provided function, `fn`, with just the first argument given.
```js
const unary = fn => val => fn(val);
```
<details>
<summary>Examples</summary>
```js
['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]
```
</details>
<br>[⬠Back to top](#table-of-contents)
---
## š Array
### all
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
Use `Array.every()` to test if all elements in the collection return `true` based on `fn`.
Omit the second argument, `fn`, to use `Boolean` as a default.
```js
const all = (arr, fn = Boolean) => arr.every(fn);
```
<details>
<summary>Examples</summary>
```js
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
```
</details>
<br>[⬠Back to top](#table-of-contents)
### allEqual
Check if all elements are equal
Use `Array.every()` to check if all the elements of the array are the same as the first one.
```js
const allEqual = arr => arr.every(val => val === arr[0]);
```
<details>
<summary>Examples</summary>
```js
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
```
</details>
<br>[⬠Back to top](#table-of-contents)
### any
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
Use `Array.some()` to test if any elements in the collection return `true` based on `fn`.
Omit the second argument, `fn`, to use `Boolean` as a default.
```js
const any = (arr, fn = Boolean) => arr.some(fn);
```
<details>
<summary>Examples</summary>
```js
any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true
```
</details>
<br>[⬠Back to top](#table-of-contents)
### arrayToCSV
Converts a 2D array to a comma-separated values (CSV) string.
Use `Array.map()` and `Array.join(delimiter)` to combine individual 1D arrays (rows) into strings.
Use `Array.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
```js
const arrayToCSV = (arr, delimiter = ',') =>
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
```
<details>
<summary>Examples</summary>
```js
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
```
</details>
<br>[⬠Back to top](#table-of-contents)
### bifurcate
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`.
```js
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
```
<details>
<summary>Examples</summary>
```js
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### bifurcateBy
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element.
```js
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
```
<details>
<summary>Examples</summary>
```js
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### chunk
Chunks an array into smaller arrays of a specified size.
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
Use `Array.slice()` to map each element of the new array to a chunk the length of `size`.
If the original array can't be split evenly, the final chunk will contain the remaining elements.
```js
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
```
<details>
<summary>Examples</summary>
```js
chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### compact
Removes falsey values from an array.
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
```js
const compact = arr => arr.filter(Boolean);
```
<details>
<summary>Examples</summary>
```js
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### countBy
Groups the elements of an array based on the given function and returns the count of elements in each group.
Use `Array.map()` to map the values of an array to a function or property name.
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
```js
const countBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
```
<details>
<summary>Examples</summary>
```js
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
```
</details>
<br>[⬠Back to top](#table-of-contents)
### countOccurrences
Counts the occurrences of a value in an array.
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
```js
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
```
<details>
<summary>Examples</summary>
```js
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
```
</details>
<br>[⬠Back to top](#table-of-contents)
### deepFlatten
Deep flattens an array.
Use recursion.
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
Recursively flatten each element that is an array.
```js
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
```
<details>
<summary>Examples</summary>
```js
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### difference
Returns the difference between two arrays.
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
```js
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
```
<details>
<summary>Examples</summary>
```js
difference([1, 2, 3], [1, 2, 4]); // [3]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### differenceBy
Returns the difference between two arrays, after applying the provided function to each array element of both.
Create a `Set` by applying `fn` to each element in `b`, then use `Array.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.
```js
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(v => fn(v)));
return a.filter(x => !s.has(fn(x)));
};
```
<details>
<summary>Examples</summary>
```js
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### differenceWith
Filters out all values from an array for which the comparator function does not return `true`.
Use `Array.filter()` and `Array.findIndex()` to find the appropriate values.
```js
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
```
<details>
<summary>Examples</summary>
```js
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### drop
Returns a new array with `n` elements removed from the left.
Use `Array.slice()` to slice the remove the specified number of elements from the left.
```js
const drop = (arr, n = 1) => arr.slice(n);
```
<details>
<summary>Examples</summary>
```js
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []
```
</details>
<br>[⬠Back to top](#table-of-contents)
### dropRight
Returns a new array with `n` elements removed from the right.
Use `Array.slice()` to slice the remove the specified number of elements from the right.
```js
const dropRight = (arr, n = 1) => arr.slice(0, -n);
```
<details>
<summary>Examples</summary>
```js
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []
```
</details>
<br>[⬠Back to top](#table-of-contents)
### dropRightWhile
Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
Loop through the array, using `Array.slice()` to drop the last element of the array until the returned value from the function is `true`.
Returns the remaining elements.
```js
const dropRightWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
};
```
<details>
<summary>Examples</summary>
```js
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### dropWhile
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`.
Returns the remaining elements.
```js
const dropWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
};
```
<details>
<summary>Examples</summary>
```js
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### everyNth
Returns every nth element in an array.
Use `Array.filter()` to create a new array that contains every nth element of a given array.
```js
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
```
<details>
<summary>Examples</summary>
```js
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### filterNonUnique
Filters out the non-unique values in an array.
Use `Array.filter()` for an array containing only the unique values.
```js
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
```
<details>
<summary>Examples</summary>
```js
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### filterNonUniqueBy
Filters out the non-unique values in an array, based on a provided comparator function.
Use `Array.filter()` and `Array.every()` for an array containing only the unique values, based on the comparator function, `fn`.
The comparator function takes four arguments: the values of the two elements being compared and their indexes.
```js
const filterNonUniqueBy = (arr, fn) =>
arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
```
<details>
<summary>Examples</summary>
```js
filterNonUniqueBy(
[
{ id: 0, value: 'a' },
{ id: 1, value: 'b' },
{ id: 2, value: 'c' },
{ id: 1, value: 'd' },
{ id: 0, value: 'e' }
],
(a, b) => a.id == b.id
); // [ { id: 2, value: 'c' } ]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### findLast
Returns the last element for which the provided function returns a truthy value.
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one.
```js
const findLast = (arr, fn) => arr.filter(fn).pop();
```
<details>
<summary>Examples</summary>
```js
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
```
</details>
<br>[⬠Back to top](#table-of-contents)
### findLastIndex
Returns the index of the last element for which the provided function returns a truthy value.
Use `Array.map()` to map each element to an array with its index and value.
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one.
```js
const findLastIndex = (arr, fn) =>
arr
.map((val, i) => [i, val])
.filter(([i, val]) => fn(val, i, arr))
.pop()[0];
```
<details>
<summary>Examples</summary>
```js
findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
```
</details>
<br>[⬠Back to top](#table-of-contents)
### flatten
Flattens an array up to the specified depth.
Use recursion, decrementing `depth` by 1 for each level of depth.
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
Base case, for `depth` equal to `1` stops recursion.
Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).
```js
const flatten = (arr, depth = 1) =>
arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
```
<details>
<summary>Examples</summary>
```js
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### forEachRight
Executes a provided function once for each array element, starting from the array's last element.
Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array.
```js
const forEachRight = (arr, callback) =>
arr
.slice(0)
.reverse()
.forEach(callback);
```
<details>
<summary>Examples</summary>
```js
forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
```
</details>
<br>[⬠Back to top](#table-of-contents)
### groupBy
Groups the elements of an array based on the given function.
Use `Array.map()` to map the values of an array to a function or property name.
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
```js
const groupBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
```
<details>
<summary>Examples</summary>
```js
groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}
groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}
```
</details>
<br>[⬠Back to top](#table-of-contents)
### head
Returns the head of a list.
Use `arr[0]` to return the first element of the passed array.
```js
const head = arr => arr[0];
```
<details>
<summary>Examples</summary>
```js
head([1, 2, 3]); // 1
```
</details>
<br>[⬠Back to top](#table-of-contents)
### indexOfAll
Returns all indices of `val` in an array. If `val` never occurs, returns `[]`.
Use `Array.reduce()` to loop over elements and store indices for matching elements.
Return the array of indices.
```js
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
```
<details>
<summary>Examples</summary>
```js
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initial
Returns all the elements of an array except the last one.
Use `arr.slice(0,-1)` to return all but the last element of the array.
```js
const initial = arr => arr.slice(0, -1);
```
<details>
<summary>Examples</summary>
```js
initial([1, 2, 3]); // [1,2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initialize2DArray
Initializes a 2D array of given width and height and value.
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
```js
const initialize2DArray = (w, h, val = null) =>
Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
```
<details>
<summary>Examples</summary>
```js
initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initializeArrayWithRange
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.
Use `Array.from()` to create an array of the desired length, `(end - start + 1)/step`, and a map function to fill it with the desired values in the given range.
You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`.
```js
const initializeArrayWithRange = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);
```
<details>
<summary>Examples</summary>
```js
initializeArrayWithRange(5); // [0,1,2,3,4,5]
initializeArrayWithRange(7, 3); // [3,4,5,6,7]
initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initializeArrayWithRangeRight
Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.
Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`.
```js
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
```
<details>
<summary>Examples</summary>
```js
initializeArrayWithRangeRight(5); // [5,4,3,2,1,0]
initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3]
initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initializeArrayWithValues
Initializes and fills an array with the specified values.
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
You can omit `val` to use a default value of `0`.
```js
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
```
<details>
<summary>Examples</summary>
```js
initializeArrayWithValues(5, 2); // [2,2,2,2,2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### initializeNDArray
Create a n-dimensional array with given value.
Use recursion.
Use `Array.map()` to generate rows where each is a new array initialized using `initializeNDArray`.
```js
const initializeNDArray = (val, ...args) =>
args.length === 0
? val
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
```
<details>
<summary>Examples</summary>
```js
initializeNDArray(1, 3); // [1,1,1]
initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### intersection
Returns a list of elements that exist in both arrays.
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
```js
const intersection = (a, b) => {
const s = new Set(b);
return a.filter(x => s.has(x));
};
```
<details>
<summary>Examples</summary>
```js
intersection([1, 2, 3], [4, 3, 2]); // [2,3]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### intersectionBy
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
Create a `Set` by applying `fn` to all elements in `b`, then use `Array.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
```js
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return a.filter(x => s.has(fn(x)));
};
```
<details>
<summary>Examples</summary>
```js
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### intersectionWith
Returns a list of elements that exist in both arrays, using a provided comparator function.
Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values.
```js
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
```
<details>
<summary>Examples</summary>
```js
intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### isSorted
Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
Calculate the ordering `direction` for the first two elements.
Use `Object.entries()` to loop over array objects and compare them in pairs.
Return `0` if the `direction` changes or the `direction` if the last element is reached.
```js
const isSorted = arr => {
let direction = -(arr[0] - arr[1]);
for (let [i, val] of arr.entries()) {
direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
if (i === arr.length - 1) return !direction ? 0 : direction;
else if ((val - arr[i + 1]) * direction > 0) return 0;
}
};
```
<details>
<summary>Examples</summary>
```js
isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0
```
</details>
<br>[⬠Back to top](#table-of-contents)
### join
Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
Use `Array.reduce()` to combine elements into a string.
Omit the second argument, `separator`, to use a default separator of `','`.
Omit the third argument, `end`, to use the same value as `separator` by default.
```js
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
i === arr.length - 2
? acc + val + end
: i === arr.length - 1
? acc + val
: acc + val + separator,
''
);
```
<details>
<summary>Examples</summary>
```js
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen"
join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen"
join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"
```
</details>
<br>[⬠Back to top](#table-of-contents)
### JSONtoCSV 
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
Use `Array.join(demiliter)` to combine all the names in `columns` to create the first row.
Use `Array.map()` and `Array.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
Use `Array.join('\n')` to combine all rows into a string.
Omit the third argument, `delimiter`, to use a default delimiter of `,`.
```js
const JSONtoCSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
```
<details>
<summary>Examples</summary>
```js
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
```
</details>
<br>[⬠Back to top](#table-of-contents)
### last
Returns the last element in an array.
Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
```js
const last = arr => arr[arr.length - 1];
```
<details>
<summary>Examples</summary>
```js
last([1, 2, 3]); // 3
```
</details>
<br>[⬠Back to top](#table-of-contents)
### longestItem
Takes any number of iterable objects or objects with a `length` property and returns the longest one.
If multiple objects have the same length, the first one will be returned.
Returns `undefined` if no arguments are provided.
Use `Array.reduce()`, comparing the `length` of objects to find the longest one.
```js
const longestItem = (val, ...vals) =>
[val, ...vals].reduce((a, x) => (x.length > a.length ? x : a));
```
<details>
<summary>Examples</summary>
```js
longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
longestItem(...['a', 'ab', 'abc']); // 'abc'
longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
longestItem([1, 2, 3], 'foobar'); // 'foobar'
```
</details>
<br>[⬠Back to top](#table-of-contents)
### mapObject 
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
```js
const mapObject = (arr, fn) =>
(a => (
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
))();
```
<details>
<summary>Examples</summary>
```js
const squareIt = arr => mapObject(arr, a => a * a);
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
```
</details>
<br>[⬠Back to top](#table-of-contents)
### maxN
Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order).
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
Use `Array.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array.
```js
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
```
<details>
<summary>Examples</summary>
```js
maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### minN
Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
Use `Array.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array.
```js
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
```
<details>
<summary>Examples</summary>
```js
minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### none
Returns `true` if the provided predicate function returns `false` for all elements in a collection, `false` otherwise.
Use `Array.some()` to test if any elements in the collection return `true` based on `fn`.
Omit the second argument, `fn`, to use `Boolean` as a default.
```js
const none = (arr, fn = Boolean) => !arr.some(fn);
```
<details>
<summary>Examples</summary>
```js
none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true
```
</details>
<br>[⬠Back to top](#table-of-contents)
### nthElement
Returns the nth element of an array.
Use `Array.slice()` to get an array containing the nth element at the first place.
If the index is out of bounds, return `undefined`.
Omit the second argument, `n`, to get the first element of the array.
```js
const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
```
<details>
<summary>Examples</summary>
```js
nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'
```
</details>
<br>[⬠Back to top](#table-of-contents)
### offset
Moves the specified amount of elements to the end of the array.
Use `Array.slice()` twice to get the elements after the specified index and the elements before that.
Use the spread operator(`...`) to combine the two into one array.
If `offset` is negative, the elements will be moved from end to start.
```js
const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
```
<details>
<summary>Examples</summary>
```js
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
```
</details>
<br>[⬠Back to top](#table-of-contents)
### partition
Groups the elements into two arrays, depending on the provided f