30-seconds-of-code 中文文档教程

发布于 6年前 浏览 27 项目主页 更新于 3年前

徽标

30 seconds of code

许可证npm 下载npm 版本已知漏洞
Travis BuildCodacy 徽章可维护性js-semistandard-style
AwesomeProductHunt Gitter chatPRs Welcome

精选的有用 JavaScript 片段集合,您可以在 30 秒或更短时间内理解这些片段。

Sponsored by DigitalOcean

  • Use Ctrl + F or command + F to search for a snippet.
  • Contributions welcome, please read the contribution guide.
  • Snippets are written in ES6, use the Babel transpiler to ensure backwards-compatibility.
  • You can import these snippets into VSCode, by following the instructions found here.
  • You can search, view and copy these snippets from a terminal, using the CLI application from this repo.
  • If you want to follow 30-seconds-of-code on social media, you can find us on Facebook, Instagram and Twitter.

Related projects

Package

⚠️ 注意:一些我们的片段尚未针对生产进行优化(请参阅个别片段问题的免责声明)。

您可以在 npm 上找到包含所有片段的包。

# With npm
npm install 30-seconds-of-code

# With yarn
yarn add 30-seconds-of-code

CDN 链接

Details

浏览器

<script src="https://unpkg.com/30-seconds-of-code@1/dist/_30s.es5.min.js"></script>
<script>
  _30s.average(1, 2, 3);
</script>

节点

// 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);

Contents

Adapter

View contents

Array

View contents

Browser

View contents

⏱️ Date

View contents

????️ Function

View contents

➗ Math

View contents

Node

View contents

????️ Object

View contents

String

View contents

Type

View contents

Utility

View contents


Adapter

ary

创建一个最多接受 n 个参数的函数,忽略任何其他参数。

使用 Array.prototype.slice(0,n) 和扩展运算符 ( <代码>...)。

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));

Examples

const firstTwoMax = ary(Math.max, 2);
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]


⬆ 返回页首

call

给定一个键和一组参数,在给定上下文时调用它们。 主要用于组合。

使用闭包调用带有存储参数的存储键。

const call = (key, ...args) => context => context[key](...args);

Examples

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 ]


⬆ 返回页首

collectInto

将接受数组的函数更改为可变参数函数。

给定一个函数,返回一个将所有输入收集到数组接受函数中的闭包。

const collectInto = fn => (...args) => fn(args);

Examples

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)


⬆ 返回页首

flip

Flip 将函数作为参数,然后将第一个参数作为最后一个参数。

返回一个接受可变输入的闭包,并在应用其余参数之前拼接最后一个参数使其成为第一个参数。

const flip = fn => (first, ...rest) => fn(...rest, first);

Examples

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


⬆ 返回页首

over

创建一个函数,该函数使用它接收的参数调用每个提供的函数并返回结果。

使用 Array.prototype.map()Function.prototype.apply() 将每个函数应用于给定的参数。

const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));

Examples

const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1,5]


⬆ 返回页首

overArgs

创建一个调用提供的函数并转换其参数的函数。

使用 Array.prototype.map()transforms 应用到 args 并结合扩展运算符 (...) 将转换后的参数传递给 fn

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));

Examples

const square = n => n * n;
const double = n => n * 2;
const fn = overArgs((x, y) => [x, y], [square, double]);
fn(9, 3); // [81, 6]


⬆ 返回顶部

pipeAsyncFunctions

为异步函数执行从左到右的函数组合。

Array.prototype.reduce() 与扩展运算符 (...) 结合使用,以使用 Promise.then()< 执行从左到右的函数组合/代码>。 这些函数可以返回以下组合:简单值、Promise,或者它们可以定义为通过 await 返回的async。 所有函数都必须是一元的。

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));

Examples

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)
})();


⬆ 返回顶部

pipeFunctions

执行从左到右的函数组合。

Array.prototype.reduce() 与扩展运算符 (...) 一起使用,以执行从左到右的函数组合。 第一个(最左边的)函数可以接受一个或多个参数; 其余函数必须是一元的。

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));

Examples

const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15


⬆ 返回页首

promisify

将异步函数转换为返回承诺。

使用柯里化返回一个函数,该函数返回调用原始函数的 Promise。 使用 ...rest 运算符传入所有参数。

在 Node 8+ 中,您可以使用 util.promisify

const promisify = func => (...args) =>
  new Promise((resolve, reject) =>
    func(...args, (err, result) => (err ? reject(err) : resolve(result)))
  );

Examples

const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s


⬆ 返回页首

rearg

创建一个调用提供的函数的函数,其参数根据指定的索引排列。

使用 Array.prototype.map() 根据 indexes 结合扩展运算符 (...) 对参数重新排序以传递转换后的结果fn 的参数。

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));

Examples

var rearged = rearg(
  function(a, b, c) {
    return [a, b, c];
  },
  [2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']


⬆ 返回页首

spreadOver

获取可变参数函数并返回一个闭包,该闭包接受要映射到函数输入的参数数组。

使用闭包和扩展运算符 (...) 将参数数组映射到函数的输入。

const spreadOver = fn => argsArr => fn(...argsArr);

Examples

const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // 3


⬆ 返回页首

unary

创建一个最多接受一个参数的函数,忽略任何其他参数。

调用提供的函数 fn,仅使用给定的第一个参数。

const unary = fn => val => fn(val);

Examples

['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]


⬆ 返回页首


Array

all

如果提供的谓词函数对集合中的所有元素返回 true,则返回 truefalse 否则。

使用 Array.prototype.every() 测试集合中的所有元素是否根据 fn 返回 true。 省略第二个参数 fn,以使用 Boolean 作为默认值。

const all = (arr, fn = Boolean) => arr.every(fn);

Examples

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true


⬆ 返回页首

allEqual

检查数组中的所有元素是否相等。

使用 Array.prototype.every() 检查数组的所有元素是否都与第一个元素相同。

const allEqual = arr => arr.every(val => val === arr[0]);

Examples

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true


⬆ 返回页首

any

如果提供的谓词函数对 a 中的至少一个元素返回 true,则返回 true集合,否则为 false

使用 Array.prototype.some() 测试集合中的任何元素是否根据 fn 返回 true。 省略第二个参数 fn,以使用 Boolean 作为默认值。

const any = (arr, fn = Boolean) => arr.some(fn);

Examples

any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true


⬆ 返回页首

arrayToCSV

将二维数组转换为逗号分隔值 (CSV) 字符串。

使用 Array.prototype.map()Array.prototype.join(delimiter) 将单个一维数组(行)组合成字符串。 使用 Array.prototype.join('\n') 将所有行组合成一个 CSV 字符串,每行用换行符分隔。 省略第二个参数 delimiter,以使用默认分隔符 ,

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');

Examples

arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'


⬆ 返回页首

bifurcate

值分成两组。 如果filter中的元素为真,则集合中对应的元素属于第一组; 否则,它属于第二组。

使用 Array.prototype.reduce()Array.prototype.push() 基于 filter 将元素添加到组中。

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

Examples

bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]


⬆ 返回页首

bifurcateBy

根据谓词函数将值分成两组,谓词函数指定输入集合中的元素属于哪一组。 如果谓词函数返回真值,则集合元素属于第一组; 否则,它属于第二组。

根据 fn 返回的值,使用 Array.prototype.reduce()Array.prototype.push() 将元素添加到组中对于每个元素。

const bifurcateBy = (arr, fn) =>
  arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);

Examples

bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]


⬆ 返回页首

chunk

将数组分块为指定大小的较小数组。

使用 Array.from() 创建一个新数组,该数组适合将要生成的块数。 使用 Array.prototype.slice() 将新数组的每个元素映射到长度为 size 的块。 如果原始数组不能被平均分割,最后的块将包含剩余的元素。

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

Examples

chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]


⬆ 返回页首

compact

从数组中删除假值。

使用 Array.prototype.filter() 过滤掉虚假值(falsenull0""未定义NaN)。

const compact = arr => arr.filter(Boolean);

Examples

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]


⬆ 返回页首

countBy

根据给定的函数对数组的元素进行分组,并返回每组中元素的数量。

使用 Array.prototype.map() 将数组的值映射到函数或属性名称。 使用 Array.prototype.reduce() 创建一个对象,其中的键是根据映射结果生成的。

const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1;
    return acc;
  }, {});

Examples

countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}


⬆ 返回页首

countOccurrences

计算数组中某个值的出现次数。

每次遇到数组中的特定值时,使用 Array.prototype.reduce() 递增计数器。

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

Examples

countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3


⬆ 返回顶部

deepFlatten

Deep 展平数组。

使用递归。 将 Array.prototype.concat() 与一个空数组 ([]) 和扩展运算符 (...) 结合使用来展平数组. 递归地展平数组中的每个元素。

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

Examples

deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]


⬆ 返回顶部

difference

返回两个数组之间的差异。

b 创建一个 Set,然后在 a 上使用 Array.prototype.filter() 只保留值而不是包含在 b 中。

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};

Examples

difference([1, 2, 3], [1, 2, 4]); // [3]


⬆ 返回页首

differenceBy

在将提供的函数应用于两个数组的每个数组元素后,返回两个数组之间的差异。

通过对 b 中的每个元素应用 fn 创建一个 Set,然后在中使用 Array.prototype.filter()a 上的 fn 结合,只保留不包含在先前创建的集合中的值。

const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => !s.has(fn(x)));
};

Examples

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 } ]


⬆ 返回页首

differenceWith

从比较器函数不返回 true 的数组中过滤掉所有值。

使用 Array.prototype.filter()Array.prototype.findIndex() 找到合适的值。

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

Examples

differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]


⬆ 返回页首

drop

返回一个新数组,其中 n 个元素从左侧移除。

使用 Array.prototype.slice() 切片并从左侧移除指定数量的元素。

const drop = (arr, n = 1) => arr.slice(n);

Examples

drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []


⬆ 返回页首

dropRight

返回一个新数组,其中 n 个元素从右侧移除。

使用 Array.prototype.slice() 切片并从右侧移除指定数量的元素。

const dropRight = (arr, n = 1) => arr.slice(0, -n);

Examples

dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []


⬆ 返回页首

dropRightWhile

从数组末尾删除元素,直到传递的函数返回 true。 返回数组中的剩余元素。

遍历数组,使用 Array.prototype.slice() 删除数组的最后一个元素,直到函数的返回值为 true。 返回剩余的元素。

const dropRightWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
  return arr;
};

Examples

dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]


⬆ 返回页首

dropWhile

删除数组中的元素,直到传递的函数返回 true。 返回数组中的剩余元素。

遍历数组,使用 Array.prototype.slice() 删除数组的第一个元素,直到函数的返回值为 true。 返回剩余的元素。

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};

Examples

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]


⬆ 返回页首

everyNth

返回数组中的第 n 个元素。

使用 Array.prototype.filter() 创建一个包含给定数组的每个第 n 个元素的新数组。

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

Examples

everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]


⬆ 返回页首

filterNonUnique

过滤掉数组中的非唯一值。

对仅包含唯一值的数组使用 Array.prototype.filter()

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

Examples

filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]


⬆ 返回页首

filterNonUniqueBy

根据提供的比较器函数过滤掉数组中的非唯一值。

根据比较函数 fn<,将 Array.prototype.filter()Array.prototype.every() 用于仅包含唯一值的数组/代码>。 比较器函数有四个参数:被比较的两个元素的值和它们的索引。

const filterNonUniqueBy = (arr, fn) =>
  arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));

Examples

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' } ]


⬆ 返回页首

findLast

返回所提供的函数为其返回真值的最后一个元素。

使用 Array.prototype.filter() 删除 fn 返回错误值的元素,使用 Array.prototype.pop() 获取最后一个一。

const findLast = (arr, fn) => arr.filter(fn).pop();

Examples

findLast([1, 2, 3, 4], n => n % 2 === 1); // 3


⬆ 返回页首

findLastIndex

返回最后一个元素的索引,所提供的函数为其返回真值。

使用 Array.prototype.map() 将每个元素映射到一个数组及其索引和值。 使用 Array.prototype.filter() 删除 fn 返回错误值的元素,使用 Array.prototype.pop() 获取最后一个一。

const findLastIndex = (arr, fn) =>
  arr
    .map((val, i) => [i, val])
    .filter(([i, val]) => fn(val, i, arr))
    .pop()[0];

Examples

findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)


⬆ 返回页首

flatten

将数组展平到指定深度。

使用递归,将每个深度级别的 depth 递减 1。 使用 Array.prototype.reduce()Array.prototype.concat() 合并元素或数组。 基本情况,对于 depth 等于 1 停止递归。 省略第二个参数 depth 以仅展平到 1 的深度(单次展平)。

const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

Examples

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]


⬆ 返回页首

forEachRight

从数组的最后一个元素开始,为每个数组元素执行一次提供的函数。

使用 Array.prototype.slice(0) 克隆给定的数组,使用 Array.prototype.reverse() 反转它,使用 Array.prototype.forEach() 遍历反转数组。

const forEachRight = (arr, callback) =>
  arr
    .slice(0)
    .reverse()
    .forEach(callback);

Examples

forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'


⬆ 返回页首

groupBy

根据给定函数对数组元素进行分组。

使用 Array.prototype.map() 将数组的值映射到函数或属性名称。 使用 Array.prototype.reduce() 创建一个对象,其中的键是根据映射结果生成的。

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;
  }, {});

Examples

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']}


⬆ 返回顶部

返回列表的头部。

使用 arr[0] 返回传入数组的第一个元素。

const head = arr => arr[0];

Examples

head([1, 2, 3]); // 1


⬆ 返回页首

indexOfAll

返回数组中 val 的所有索引。 如果 val 从未发生,则返回 []

使用 Array.prototype.reduce() 遍历元素并存储匹配元素的索引。 返回索引数组。

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

Examples

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []


⬆ 返回页首

initial

返回数组中除最后一个元素之外的所有元素。

使用 arr.slice(0,-1) 返回数组中除最后一个元素之外的所有元素。

const initial = arr => arr.slice(0, -1);

Examples

initial([1, 2, 3]); // [1,2]


⬆ 返回页首

initialize2DArray

初始化给定宽度、高度和值的二维数组。

使用 Array.prototype.map() 生成 h 行,其中每行都是一个大小为 w 并用值初始化的新数组。 如果未提供该值,则默认为 null

const initialize2DArray = (w, h, val = null) =>
  Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));

Examples

initialize2DArray(2, 2, 0); // [[0,0], [0,0]]


⬆ 返回顶部

initializeArrayWithRange

初始化一个包含指定范围内的数字的数组,其中 startend 包括在内它们的共同区别是 step

使用 Array.from() 创建所需长度的数组,(end - start + 1)/step,并使用 map 函数用所需的值填充数组在给定的范围内。 您可以省略 start 以使用默认值 0。 您可以省略 step 以使用默认值 1

const initializeArrayWithRange = (end, start = 0, step = 1) =>
  Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);

Examples

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]


⬆ 返回页首

initializeArrayWithRangeRight

初始化一个数组,其中包含指定范围内的数字(反向),其中 startend code> 包含它们的共同区别 step

使用 Array.from(Math.ceil((end+1-start)/step)) 创建所需长度的数组(元素数量等于 (end-start )/step(end+1-start)/step 包含结束), Array.prototype.map() 填充所需的值一个范围。 您可以省略 start 以使用默认值 0。 您可以省略 step 以使用默认值 1

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
  );

Examples

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]


⬆ 返回页首

initializeArrayWithValues

初始化数组并用指定值填充数组。

使用 Array(n) 创建所需长度的数组,使用 fill(v) 用所需的值填充它。 您可以省略 val 以使用默认值 0

const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);

Examples

initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]


⬆ 返回页首

initializeNDArray

创建一个具有给定值的 n 维数组。

使用递归。 使用 Array.prototype.map() 生成行,其中每行都是使用 initializeNDArray 初始化的新数组。

const initializeNDArray = (val, ...args) =>
  args.length === 0
    ? val
    : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));

Examples

initializeNDArray(1, 3); // [1,1,1]
initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]


⬆ 返回页首

intersection

返回两个数组中都存在的元素列表。

b 创建一个 Set,然后在 a 上使用 Array.prototype.filter() 以仅保留包含的值在 b 中。

const intersection = (a, b) => {
  const s = new Set(b);
  return a.filter(x => s.has(x));
};

Examples

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]


⬆ 返回页首

intersectionBy

在将提供的函数应用于两个数组的每个数组元素后,返回两个数组中都存在的元素列表。

通过将 fn 应用于 b 中的所有元素来创建一个 Set,然后使用 Array.prototype.filter() a 只保留元素,当 fn 应用于它们时,这些元素会产生包含在 b 中的值。

const intersectionBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => s.has(fn(x)));
};

Examples

intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]


⬆ 返回页首

intersectionWith

使用提供的比较函数返回两个数组中都存在的元素列表。

Array.prototype.filter()Array.prototype.findIndex() 与提供的比较器结合使用以确定相交值。

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);

Examples

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]


⬆ 返回页首

isSorted

如果数组按升序排序,则返回 1,否则返回 -1按降序排序,如果未排序,则为 0

计算前两个元素的排序 direction。 使用 Object.entries() 遍历数组对象并成对比较它们。 如果 direction 发生变化,则返回 0;如果到达最后一个元素,则返回 direction

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;
  }
};

Examples

isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0


⬆ 返回页首

join

将数组的所有元素连接成一个字符串并返回该字符串。 使用分隔符和结束分隔符。

使用 Array.prototype.reduce() 将元素组合成一个字符串。 省略第二个参数 separator,以使用默认分隔符 ','。 省略第三个参数 end,默认使用与 separator 相同的值。

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,
    ''
  );

Examples

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"


⬆ 返回页首

JSONtoCSV advanced

将对象数组转换为逗号分隔值 (CSV) 字符串,该字符串仅包含指定的

使用 Array.prototype.join(delimiter) 组合 columns 中的所有名称以创建第一行。 使用 Array.prototype.map()Array.prototype.reduce() 为每个对象创建一行,将不存在的值替换为空字符串和仅映射值在中。 使用 Array.prototype.join('\n') 将所有行组合成一个字符串。 省略第三个参数 delimiter,以使用默认分隔符 ,

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');

Examples

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"'


⬆ 返回页首

last

返回数组中的最后一个元素。

使用 arr.length - 1 计算给定数组最后一个元素的索引并返回它。

const last = arr => arr[arr.length - 1];

Examples

last([1, 2, 3]); // 3


⬆ 返回页首

longestItem

获取任意数量的可迭代对象或具有 length 属性的对象并返回最长的一个。 如果多个对象的长度相同,则返回第一个。 如果未提供参数,则返回 undefined

使用Array.prototype.reduce(),比较对象的length,找出最长的一个。

const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a));

Examples

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'


⬆ 返回顶部

mapObject advanced

使用函数将数组的值映射到对象,其中键值对由作为键的原始值和映射的值组成价值。

使用匿名内部函数范围声明未定义的内存空间,使用闭包存储返回值。 使用新的 Array 来存储数组及其数据集上的函数映射和逗号运算符以返回第二步,而无需从一个上下文移动到另一个上下文(由于闭包和顺序的操作)。

const mapObject = (arr, fn) =>
  (a => (
    (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
  ))();

Examples

const squareIt = arr => mapObject(arr, a => a * a);
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }


⬆ 返回顶部

maxN

从提供的数组中返回 n 个最大元素。 如果 n 大于或等于提供的数组长度,则返回原始数组(按降序排序)。

使用 Array.prototype.sort() 结合扩展运算符 (...) 创建数组的浅表克隆并按降序对其进行排序。 使用 Array.prototype.slice() 获取指定数量的元素。 省略第二个参数 n,以获得单元素数组。

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);

Examples

maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2]


⬆ 返回页首

minN

从提供的数组中返回 n 个最小元素。 如果 n 大于或等于提供的数组长度,则返回原始数组(按升序排序)。

使用 Array.prototype.sort() 结合扩展运算符 (...) 创建数组的浅表克隆并按升序对其进行排序。 使用 Array.prototype.slice() 获取指定数量的元素。 省略第二个参数 n,以获得单元素数组。

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);

Examples

minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]


⬆ 返回页首

none

如果提供的谓词函数对集合中的所有元素返回 false,则返回 truefalse 否则。

使用 Array.prototype.some() 测试集合中的任何元素是否根据 fn 返回 true。 省略第二个参数 fn,以使用 Boolean 作为默认值。

const none = (arr, fn = Boolean) => !arr.some(fn);

Examples

none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true


⬆ 返回页首

nthElement

返回数组的第 n 个元素。

使用 Array.prototype.slice() 获取第一个包含第 n 个元素的数组。 如果索引超出范围,则返回 undefined。 省略第二个参数 n,以获取数组的第一个元素。

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];

Examples

nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'


⬆ 返回页首

offset

将指定数量的元素移动到数组末尾。

使用 Array.prototype.slice() 两次获取指定索引之后的元素和之前的元素。 使用扩展运算符 (...) 将两者组合成一个数组。 如果 offset 为负数,元素将从末尾移动到开始。

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];

Examples

offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]


⬆ 返回页首

partition

根据提供的函数对每个元素的真实性,将元素分组到两个数组中。

使用 Array.prototype.reduce() 创建一个包含两个数组的数组。 使用 Array.prototype.push()fn 返回 true 的元素添加到第一个数组和 fn< /code> 返回 false 给第二个。

const partition = (arr, fn) =>
  arr.reduce(
    (acc, val, i, arr) => {
      acc[fn(val, i, arr) ? 0 : 1].push(val);
      return acc;
    },
    [[], []]
  );

Examples

const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
partition(users, o => o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]


⬆ 返回顶部

permutations advanced

⚠️ 警告:此函数的执行时间随每个数组元素呈指数增长。 超过 8 到 10 个条目将导致您的浏览器在尝试解决所有不同组合时挂起。

生成数组元素的所有排列(包含重复项)。

使用递归。 对于给定数组中的每个元素,为其其余元素创建所有部分排列。 使用 Array.prototype.map() 将元素与每个部分排列组合,然后使用 Array.prototype.reduce() 将所有排列组合到一个数组中。 基本情况是数组 length 等于 21

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
      ),
    []
  );
};

Examples

permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]


⬆ 返回页首

pull

改变原始数组以过滤掉指定的值。

使用 Array.prototype.filter()Array.prototype.includes() 提取不需要的值。 使用 Array.prototype.length = 0 通过将其长度重置为零来改变传入的数组,并使用 Array.prototype.push() 重新填充它拉取的值。

(对于不改变原始数组的片段,请参阅without

const pull = (arr, ...args) => {
  let argState = Array.isArray(args[0]) ? args[0] : args;
  let pulled = arr.filter((v, i) => !argState.includes(v));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
};

Examples

let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]


⬆ 返回页首

pullAtIndex advanced

改变原始数组以过滤掉指定索引处的值。

使用 Array.prototype.filter()Array.prototype.includes() 提取不需要的值。 使用 Array.prototype.length = 0 通过将其长度重置为零来改变传入的数组,并使用 Array.prototype.push() 重新填充它拉取的值。 使用 Array.prototype.push() 跟踪提取的值

const pullAtIndex = (arr, pullArr) => {
  let removed = [];
  let pulled = arr
    .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
    .filter((v, i) => !pullArr.includes(i));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
  return removed;
};

Examples

let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]


⬆ 返回页首

pullAtValue advanced

改变原始数组以过滤掉指定的值。 返回删除的元素。

使用 Array.prototype.filter()Array.prototype.includes() 提取不需要的值。 使用 Array.prototype.length = 0 通过将其长度重置为零来改变传入的数组,并使用 Array.prototype.push() 重新填充它拉取的值。 使用 Array.prototype.push() 跟踪提取的值

const pullAtValue = (arr, pullArr) => {
  let removed = [],
    pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),
    mutateTo = arr.filter((v, i) => !pullArr.includes(v));
  arr.length = 0;
  mutateTo.forEach(v => arr.push(v));
  return removed;
};

Examples

let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]


⬆ 返回页首

pullBy advanced

根据给定的迭代器函数,改变原始数组以过滤掉指定的值。

检查函数中是否提供了最后一个参数。 使用 Array.prototype.map() 将迭代器函数 fn 应用于所有数组元素。 使用 Array.prototype.filter()Array.prototype.includes() 提取不需要的值。 使用 Array.prototype.length = 0 通过将其长度重置为零来改变传入的数组,并使用 Array.prototype.push() 重新填充它拉取的值。

const pullBy = (arr, ...args) => {
  const length = args.length;
  let fn = length > 1 ? args[length - 1] : undefined;
  fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
  let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val));
  let pulled = arr.filter((v, i) => !argState.includes(fn(v)));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
};

Examples

var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];
pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]


⬆ 返回页首

reducedFilter

根据条件过滤对象数组,同时过滤掉未指定的键。

使用 Array.prototype.filter() 根据谓词 fn 过滤数组,以便它返回条件返回真值的对象。 在过滤后的数组上,使用 Array.prototype.map() 返回新对象,使用 Array.prototype.reduce() 过滤掉未提供的键keys 参数。

const reducedFilter = (data, keys, fn) =>
  data.filter(fn).map(el =>
    keys.reduce((acc, key) => {
      acc[key] = el[key];
      return acc;
    }, {})
  );

Examples

const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];

reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]


⬆ 返回页首

reduceSuccessive

对累加器和数组中的每个元素应用一个函数(从左到右),返回一个连续减少值的数组。

使用 Array.prototype.reduce() 将给定函数应用于给定数组,存储每个新结果。

const reduceSuccessive = (arr, fn, acc) =>
  arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);

Examples

reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]


⬆ 返回页首

reduceWhich

在应用提供的函数设置比较规则后,返回数组的最小值/最大值。

结合使用 Array.prototype.reduce()comparator 函数来获取数组中的适当元素。 您可以省略第二个参数 comparator,以使用返回数组中最小元素的默认参数。

const reduceWhich = (arr, comparator = (a, b) => a - b) =>
  arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));

Examples

reduceWhich([1, 3, 2]); // 1
reduceWhich([1, 3, 2], (a, b) => b - a); // 3
reduceWhich(
  [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],
  (a, b) => a.age - b.age
); // {name: "Lucy", age: 9}


⬆ 返回页首

reject

采用谓词和数组,如 Array.prototype.filter(),但只保留 x< /code> 如果 pred(x) === false

const reject = (pred, array) => array.filter((...args) => !pred(...args));

Examples

reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']


⬆ 返回页首

remove

从给定函数返回 false 的数组中删除元素。

使用 Array.prototype.filter() 查找返回真值的数组元素,使用 Array.prototype.reduce() 使用 Array.prototype.splice 删除元素()。 func 使用三个参数(value、index、array)调用。

const remove = (arr, func) =>
  Array.isArray(arr)
    ? arr.filter(func).reduce((acc, val) => {
      arr.splice(arr.indexOf(val), 1);
      return acc.concat(val);
    }, [])
    : [];

Examples

remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]


⬆ 返回页首

sample

从数组中返回一个随机元素。

使用 Math.random() 生成随机数,将其乘以 length 并使用 Math.floor()。 此方法也适用于字符串。

const sample = arr => arr[Math.floor(Math.random() * arr.length)];

Examples

sample([3, 7, 9, 11]); // 9


⬆ 返回顶部

sampleSize

array 的唯一键处获取 n 个随机元素,最大大小为 数组。

使用 Fisher-Yates 算法 打乱数组。 使用 Array.prototype.slice() 获取第一个 n 元素。 省略第二个参数 n 以仅从数组中随机获取一个元素。

const sampleSize = ([...arr], n = 1) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr.slice(0, n);
};

Examples

sampleSize([1, 2, 3], 2); // [3,1]
sampleSize([1, 2, 3], 4); // [2,3,1]


⬆ 返回顶部

shank

Array.prototype.splice(),但返回一个新数组而不是改变原始数组。

在删除现有元素和/或添加新元素后,使用 Array.prototype.slice()Array.prototype.concat() 获取包含新内容的新数组。 省略第二个参数 index,从 0 开始。 省略第三个参数 delCount,以删除 0 元素。 省略第四个参数 elements,以便不添加任何新元素。

const shank = (arr, index = 0, delCount = 0, ...elements) =>
  arr
    .slice(0, index)
    .concat(elements)
    .concat(arr.slice(index + delCount));

Examples

const names = ['alpha', 'bravo', 'charlie'];
const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]
const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
console.log(names); // ['alpha', 'bravo', 'charlie']


⬆ 返回页首

shuffle

随机化数组值的顺序,返回一个新数组。

使用 Fisher-Yates 算法 对数组元素重新排序。

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

Examples

const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]


⬆ 返回页首

similarity

返回出现在两个数组中的元素数组。

使用 Array.prototype.filter() 删除不属于 values 的值,使用 Array.prototype.includes() 确定。

const similarity = (arr, values) => arr.filter(v => values.includes(v));

Examples

similarity([1, 2, 3], [1, 2, 4]); // [1, 2]


⬆ Back to top

sortedIndex

Returns the lowest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.prototype.findIndex() to find the appropriate index where the element should be inserted.

const sortedIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
  return index === -1 ? arr.length : index;
};

Examples

sortedIndex([5, 3, 2, 1], 4); // 1
sortedIndex([30, 50], 40); // 1


⬆ Back to top

sortedIndexBy

Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

Check if the array is sorted in descending order (loosely). Use Array.prototype.findIndex() to find the appropriate index where the element should be inserted, based on the iterator function fn.

const sortedIndexBy = (arr, n, fn) => {
  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
  const val = fn(n);
  const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el)));
  return index === -1 ? arr.length : index;
};

Examples

sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0


⬆ Back to top

sortedLastIndex

Returns the highest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.prototype.reverse() and Array.prototype.findIndex() to find the appropriate last index where the element should be inserted.

const sortedLastIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el));
  return index === -1 ? 0 : arr.length - index;
};

Examples

sortedLastIndex([10, 20, 30, 30, 40], 30); // 4


⬆ Back to top

sor

Logo

30 seconds of code

Licensenpm Downloadsnpm VersionKnown Vulnerabilities
Travis BuildCodacy BadgeMaintainabilityjs-semistandard-style
AwesomeProductHuntGitter chatPRs Welcome

Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

Sponsored by DigitalOcean

  • Use Ctrl + F or command + F to search for a snippet.
  • Contributions welcome, please read the contribution guide.
  • Snippets are written in ES6, use the Babel transpiler to ensure backwards-compatibility.
  • You can import these snippets into VSCode, by following the instructions found here.
  • You can search, view and copy these snippets from a terminal, using the CLI application from this repo.
  • If you want to follow 30-seconds-of-code on social media, you can find us on Facebook, Instagram and Twitter.

Related projects

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.

# With npm
npm install 30-seconds-of-code

# With yarn
yarn add 30-seconds-of-code

CDN link

Details

Browser

<script src="https://unpkg.com/30-seconds-of-code@1/dist/_30s.es5.min.js"></script>
<script>
  _30s.average(1, 2, 3);
</script>

Node

// 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);

Contents

???? Adapter

View contents

???? Array

View contents

???? Browser

View contents

⏱️ Date

View contents

????️ Function

View contents

➗ Math

View contents

???? Node

View contents

????️ Object

View contents

???? String

View contents

???? Type

View contents

???? Utility

View contents


???? 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.prototype.slice(0,n) and the spread operator (...).

const ary = (fn, n) => (...args) => fn(...args.slice(0, n));

Examples

const firstTwoMax = ary(Math.max, 2);
[[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]


⬆ Back to top

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.

const call = (key, ...args) => context => context[key](...args);

Examples

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 ]


⬆ Back to top

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.

const collectInto = fn => (...args) => fn(args);

Examples

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)


⬆ Back to top

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.

const flip = fn => (first, ...rest) => fn(...rest, first);

Examples

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


⬆ Back to top

over

Creates a function that invokes each provided function with the arguments it receives and returns the results.

Use Array.prototype.map() and Function.prototype.apply() to apply each function to the given arguments.

const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));

Examples

const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1,5]


⬆ Back to top

overArgs

Creates a function that invokes the provided function with its arguments transformed.

Use Array.prototype.map() to apply transforms to args in combination with the spread operator (...) to pass the transformed arguments to fn.

const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));

Examples

const square = n => n * n;
const double = n => n * 2;
const fn = overArgs((x, y) => [x, y], [square, double]);
fn(9, 3); // [81, 6]


⬆ Back to top

pipeAsyncFunctions

Performs left-to-right function composition for asynchronous functions.

Use Array.prototype.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.

const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));

Examples

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)
})();


⬆ Back to top

pipeFunctions

Performs left-to-right function composition.

Use Array.prototype.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.

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));

Examples

const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15


⬆ Back to top

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

const promisify = func => (...args) =>
  new Promise((resolve, reject) =>
    func(...args, (err, result) => (err ? reject(err) : resolve(result)))
  );

Examples

const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s


⬆ Back to top

rearg

Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

Use Array.prototype.map() to reorder arguments based on indexes in combination with the spread operator (...) to pass the transformed arguments to fn.

const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));

Examples

var rearged = rearg(
  function(a, b, c) {
    return [a, b, c];
  },
  [2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']


⬆ Back to top

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.

const spreadOver = fn => argsArr => fn(...argsArr);

Examples

const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // 3


⬆ Back to top

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.

const unary = fn => val => fn(val);

Examples

['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]


⬆ Back to top


???? Array

all

Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.

Use Array.prototype.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.

const all = (arr, fn = Boolean) => arr.every(fn);

Examples

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true


⬆ Back to top

allEqual

Check if all elements in an array are equal.

Use Array.prototype.every() to check if all the elements of the array are the same as the first one.

const allEqual = arr => arr.every(val => val === arr[0]);

Examples

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true


⬆ Back to top

any

Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.

Use Array.prototype.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.

const any = (arr, fn = Boolean) => arr.some(fn);

Examples

any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true


⬆ Back to top

arrayToCSV

Converts a 2D array to a comma-separated values (CSV) string.

Use Array.prototype.map() and Array.prototype.join(delimiter) to combine individual 1D arrays (rows) into strings. Use Array.prototype.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 ,.

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');

Examples

arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'


⬆ Back to top

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.prototype.reduce() and Array.prototype.push() to add elements to groups, based on filter.

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

Examples

bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]


⬆ Back to top

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.prototype.reduce() and Array.prototype.push() to add elements to groups, based on the value returned by fn for each element.

const bifurcateBy = (arr, fn) =>
  arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);

Examples

bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]


⬆ Back to top

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.prototype.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.

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

Examples

chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]


⬆ Back to top

compact

Removes falsey values from an array.

Use Array.prototype.filter() to filter out falsey values (false, null, 0, "", undefined, and NaN).

const compact = arr => arr.filter(Boolean);

Examples

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]


⬆ Back to top

countBy

Groups the elements of an array based on the given function and returns the count of elements in each group.

Use Array.prototype.map() to map the values of an array to a function or property name. Use Array.prototype.reduce() to create an object, where the keys are produced from the mapped results.

const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
    acc[val] = (acc[val] || 0) + 1;
    return acc;
  }, {});

Examples

countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}


⬆ Back to top

countOccurrences

Counts the occurrences of a value in an array.

Use Array.prototype.reduce() to increment a counter each time you encounter the specific value inside the array.

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

Examples

countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3


⬆ Back to top

deepFlatten

Deep flattens an array.

Use recursion. Use Array.prototype.concat() with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

Examples

deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]


⬆ Back to top

difference

Returns the difference between two arrays.

Create a Set from b, then use Array.prototype.filter() on a to only keep values not contained in b.

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};

Examples

difference([1, 2, 3], [1, 2, 4]); // [3]


⬆ Back to top

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.prototype.filter() in combination with fn on a to only keep values not contained in the previously created set.

const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => !s.has(fn(x)));
};

Examples

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 } ]


⬆ Back to top

differenceWith

Filters out all values from an array for which the comparator function does not return true.

Use Array.prototype.filter() and Array.prototype.findIndex() to find the appropriate values.

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

Examples

differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]


⬆ Back to top

drop

Returns a new array with n elements removed from the left.

Use Array.prototype.slice() to slice the remove the specified number of elements from the left.

const drop = (arr, n = 1) => arr.slice(n);

Examples

drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []


⬆ Back to top

dropRight

Returns a new array with n elements removed from the right.

Use Array.prototype.slice() to slice the remove the specified number of elements from the right.

const dropRight = (arr, n = 1) => arr.slice(0, -n);

Examples

dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []


⬆ Back to top

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.prototype.slice() to drop the last element of the array until the returned value from the function is true. Returns the remaining elements.

const dropRightWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
  return arr;
};

Examples

dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]


⬆ Back to top

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.prototype.slice() to drop the first element of the array until the returned value from the function is true. Returns the remaining elements.

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};

Examples

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]


⬆ Back to top

everyNth

Returns every nth element in an array.

Use Array.prototype.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

Examples

everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]


⬆ Back to top

filterNonUnique

Filters out the non-unique values in an array.

Use Array.prototype.filter() for an array containing only the unique values.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

Examples

filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]


⬆ Back to top

filterNonUniqueBy

Filters out the non-unique values in an array, based on a provided comparator function.

Use Array.prototype.filter() and Array.prototype.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.

const filterNonUniqueBy = (arr, fn) =>
  arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));

Examples

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' } ]


⬆ Back to top

findLast

Returns the last element for which the provided function returns a truthy value.

Use Array.prototype.filter() to remove elements for which fn returns falsey values, Array.prototype.pop() to get the last one.

const findLast = (arr, fn) => arr.filter(fn).pop();

Examples

findLast([1, 2, 3, 4], n => n % 2 === 1); // 3


⬆ Back to top

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

Use Array.prototype.map() to map each element to an array with its index and value. Use Array.prototype.filter() to remove elements for which fn returns falsey values, Array.prototype.pop() to get the last one.

const findLastIndex = (arr, fn) =>
  arr
    .map((val, i) => [i, val])
    .filter(([i, val]) => fn(val, i, arr))
    .pop()[0];

Examples

findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)


⬆ Back to top

flatten

Flattens an array up to the specified depth.

Use recursion, decrementing depth by 1 for each level of depth. Use Array.prototype.reduce() and Array.prototype.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).

const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

Examples

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]


⬆ Back to top

forEachRight

Executes a provided function once for each array element, starting from the array's last element.

Use Array.prototype.slice(0) to clone the given array, Array.prototype.reverse() to reverse it and Array.prototype.forEach() to iterate over the reversed array.

const forEachRight = (arr, callback) =>
  arr
    .slice(0)
    .reverse()
    .forEach(callback);

Examples

forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'


⬆ Back to top

groupBy

Groups the elements of an array based on the given function.

Use Array.prototype.map() to map the values of an array to a function or property name. Use Array.prototype.reduce() to create an object, where the keys are produced from the mapped results.

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;
  }, {});

Examples

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']}


⬆ Back to top

Returns the head of a list.

Use arr[0] to return the first element of the passed array.

const head = arr => arr[0];

Examples

head([1, 2, 3]); // 1


⬆ Back to top

indexOfAll

Returns all indices of val in an array. If val never occurs, returns [].

Use Array.prototype.reduce() to loop over elements and store indices for matching elements. Return the array of indices.

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

Examples

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []


⬆ Back to top

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.

const initial = arr => arr.slice(0, -1);

Examples

initial([1, 2, 3]); // [1,2]


⬆ Back to top

initialize2DArray

Initializes a 2D array of given width and height and value.

Use Array.prototype.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.

const initialize2DArray = (w, h, val = null) =>
  Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));

Examples

initialize2DArray(2, 2, 0); // [[0,0], [0,0]]


⬆ Back to top

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.

const initializeArrayWithRange = (end, start = 0, step = 1) =>
  Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start);

Examples

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]


⬆ Back to top

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.prototype.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.

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
  );

Examples

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]


⬆ Back to top

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.

const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);

Examples

initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]


⬆ Back to top

initializeNDArray

Create a n-dimensional array with given value.

Use recursion. Use Array.prototype.map() to generate rows where each is a new array initialized using initializeNDArray.

const initializeNDArray = (val, ...args) =>
  args.length === 0
    ? val
    : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));

Examples

initializeNDArray(1, 3); // [1,1,1]
initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]


⬆ Back to top

intersection

Returns a list of elements that exist in both arrays.

Create a Set from b, then use Array.prototype.filter() on a to only keep values contained in b.

const intersection = (a, b) => {
  const s = new Set(b);
  return a.filter(x => s.has(x));
};

Examples

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]


⬆ Back to top

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.prototype.filter() on a to only keep elements, which produce values contained in b when fn is applied to them.

const intersectionBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => s.has(fn(x)));
};

Examples

intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]


⬆ Back to top

intersectionWith

Returns a list of elements that exist in both arrays, using a provided comparator function.

Use Array.prototype.filter() and Array.prototype.findIndex() in combination with the provided comparator to determine intersecting values.

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);

Examples

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]


⬆ Back to top

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.

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;
  }
};

Examples

isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0


⬆ Back to top

join

Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.

Use Array.prototype.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.

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,
    ''
  );

Examples

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"


⬆ Back to top

JSONtoCSV advanced

Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

Use Array.prototype.join(delimiter) to combine all the names in columns to create the first row. Use Array.prototype.map() and Array.prototype.reduce() to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns. Use Array.prototype.join('\n') to combine all rows into a string. Omit the third argument, delimiter, to use a default delimiter of ,.

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');

Examples

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"'


⬆ Back to top

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.

const last = arr => arr[arr.length - 1];

Examples

last([1, 2, 3]); // 3


⬆ Back to top

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.prototype.reduce(), comparing the length of objects to find the longest one.

const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a));

Examples

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'


⬆ Back to top

mapObject advanced

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).

const mapObject = (arr, fn) =>
  (a => (
    (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
  ))();

Examples

const squareIt = arr => mapObject(arr, a => a * a);
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }


⬆ Back to top

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.prototype.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.prototype.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);

Examples

maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2]


⬆ Back to top

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.prototype.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.prototype.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);

Examples

minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]


⬆ Back to top

none

Returns true if the provided predicate function returns false for all elements in a collection, false otherwise.

Use Array.prototype.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.

const none = (arr, fn = Boolean) => !arr.some(fn);

Examples

none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true


⬆ Back to top

nthElement

Returns the nth element of an array.

Use Array.prototype.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.

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];

Examples

nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'


⬆ Back to top

offset

Moves the specified amount of elements to the end of the array.

Use Array.prototype.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.

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];

Examples

offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]


⬆ Back to top

partition

Groups the elements into two arrays, depending on the provided function's truthiness for each element.

Use Array.prototype.reduce() to create an array of two arrays. Use Array.prototype.push() to add elements for which fn returns true to the first array and elements for which fn returns false to the second one.

const partition = (arr, fn) =>
  arr.reduce(
    (acc, val, i, arr) => {
      acc[fn(val, i, arr) ? 0 : 1].push(val);
      return acc;
    },
    [[], []]
  );

Examples

const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
partition(users, o => o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]


⬆ Back to top

permutations advanced

⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of an array's elements (contains duplicates).

Use recursion. For each element in the given array, create all the partial permutations for the rest of its elements. Use Array.prototype.map() to combine the element with each partial permutation, then Array.prototype.reduce() to combine all permutations in one array. Base cases are for array length equal to 2 or 1.

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
      ),
    []
  );
};

Examples

permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]


⬆ Back to top

pull

Mutates the original array to filter out the values specified.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values.

(For a snippet that does not mutate the original array see without)

const pull = (arr, ...args) => {
  let argState = Array.isArray(args[0]) ? args[0] : args;
  let pulled = arr.filter((v, i) => !argState.includes(v));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
};

Examples

let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]


⬆ Back to top

pullAtIndex advanced

Mutates the original array to filter out the values at the specified indexes.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values. Use Array.prototype.push() to keep track of pulled values

const pullAtIndex = (arr, pullArr) => {
  let removed = [];
  let pulled = arr
    .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
    .filter((v, i) => !pullArr.includes(i));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
  return removed;
};

Examples

let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]


⬆ Back to top

pullAtValue advanced

Mutates the original array to filter out the values specified. Returns the removed elements.

Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values. Use Array.prototype.push() to keep track of pulled values

const pullAtValue = (arr, pullArr) => {
  let removed = [],
    pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),
    mutateTo = arr.filter((v, i) => !pullArr.includes(v));
  arr.length = 0;
  mutateTo.forEach(v => arr.push(v));
  return removed;
};

Examples

let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]


⬆ Back to top

pullBy advanced

Mutates the original array to filter out the values specified, based on a given iterator function.

Check if the last argument provided in a function. Use Array.prototype.map() to apply the iterator function fn to all array elements. Use Array.prototype.filter() and Array.prototype.includes() to pull out the values that are not needed. Use Array.prototype.length = 0 to mutate the passed in an array by resetting it's length to zero and Array.prototype.push() to re-populate it with only the pulled values.

const pullBy = (arr, ...args) => {
  const length = args.length;
  let fn = length > 1 ? args[length - 1] : undefined;
  fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
  let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val));
  let pulled = arr.filter((v, i) => !argState.includes(fn(v)));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
};

Examples

var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }];
pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]


⬆ Back to top

reducedFilter

Filter an array of objects based on a condition while also filtering out unspecified keys.

Use Array.prototype.filter() to filter the array based on the predicate fn so that it returns the objects for which the condition returned a truthy value. On the filtered array, use Array.prototype.map() to return the new object using Array.prototype.reduce() to filter out the keys which were not supplied as the keys argument.

const reducedFilter = (data, keys, fn) =>
  data.filter(fn).map(el =>
    keys.reduce((acc, key) => {
      acc[key] = el[key];
      return acc;
    }, {})
  );

Examples

const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];

reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]


⬆ Back to top

reduceSuccessive

Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.

Use Array.prototype.reduce() to apply the given function to the given array, storing each new result.

const reduceSuccessive = (arr, fn, acc) =>
  arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);

Examples

reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]


⬆ Back to top

reduceWhich

Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.

Use Array.prototype.reduce() in combination with the comparator function to get the appropriate element in the array. You can omit the second parameter, comparator, to use the default one that returns the minimum element in the array.

const reduceWhich = (arr, comparator = (a, b) => a - b) =>
  arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));

Examples

reduceWhich([1, 3, 2]); // 1
reduceWhich([1, 3, 2], (a, b) => b - a); // 3
reduceWhich(
  [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],
  (a, b) => a.age - b.age
); // {name: "Lucy", age: 9}


⬆ Back to top

reject

Takes a predicate and array, like Array.prototype.filter(), but only keeps x if pred(x) === false.

const reject = (pred, array) => array.filter((...args) => !pred(...args));

Examples

reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']


⬆ Back to top

remove

Removes elements from an array for which the given function returns false.

Use Array.prototype.filter() to find array elements that return truthy values and Array.prototype.reduce() to remove elements using Array.prototype.splice(). The func is invoked with three arguments (value, index, array).

const remove = (arr, func) =>
  Array.isArray(arr)
    ? arr.filter(func).reduce((acc, val) => {
      arr.splice(arr.indexOf(val), 1);
      return acc.concat(val);
    }, [])
    : [];

Examples

remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]


⬆ Back to top

sample

Returns a random element from an array.

Use Math.random() to generate a random number, multiply it by length and round it off to the nearest whole number using Math.floor(). This method also works with strings.

const sample = arr => arr[Math.floor(Math.random() * arr.length)];

Examples

sample([3, 7, 9, 11]); // 9


⬆ Back to top

sampleSize

Gets n random elements at unique keys from array up to the size of array.

Shuffle the array using the Fisher-Yates algorithm. Use Array.prototype.slice() to get the first n elements. Omit the second argument, n to get only one element at random from the array.

const sampleSize = ([...arr], n = 1) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr.slice(0, n);
};

Examples

sampleSize([1, 2, 3], 2); // [3,1]
sampleSize([1, 2, 3], 4); // [2,3,1]


⬆ Back to top

shank

Has the same functionality as Array.prototype.splice(), but returning a new array instead of mutating the original array.

Use Array.prototype.slice() and Array.prototype.concat() to get a new array with the new contents after removing existing elements and/or adding new elements. Omit the second argument, index, to start at 0. Omit the third argument, delCount, to remove 0 elements. Omit the fourth argument, elements, in order to not add any new elements.

const shank = (arr, index = 0, delCount = 0, ...elements) =>
  arr
    .slice(0, index)
    .concat(elements)
    .concat(arr.slice(index + delCount));

Examples

const names = ['alpha', 'bravo', 'charlie'];
const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]
const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
console.log(names); // ['alpha', 'bravo', 'charlie']


⬆ Back to top

shuffle

Randomizes the order of the values of an array, returning a new array.

Uses the Fisher-Yates algorithm to reorder the elements of the array.

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

Examples

const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]


⬆ Back to top

similarity

Returns an array of elements that appear in both arrays.

Use Array.prototype.filter() to remove values that are not part of values, determined using Array.prototype.includes().

const similarity = (arr, values) => arr.filter(v => values.includes(v));

Examples

similarity([1, 2, 3], [1, 2, 4]); // [1, 2]


⬆ Back to top

sortedIndex

Returns the lowest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.prototype.findIndex() to find the appropriate index where the element should be inserted.

const sortedIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
  return index === -1 ? arr.length : index;
};

Examples

sortedIndex([5, 3, 2, 1], 4); // 1
sortedIndex([30, 50], 40); // 1


⬆ Back to top

sortedIndexBy

Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

Check if the array is sorted in descending order (loosely). Use Array.prototype.findIndex() to find the appropriate index where the element should be inserted, based on the iterator function fn.

const sortedIndexBy = (arr, n, fn) => {
  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
  const val = fn(n);
  const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el)));
  return index === -1 ? arr.length : index;
};

Examples

sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0


⬆ Back to top

sortedLastIndex

Returns the highest index at which value should be inserted into array in order to maintain its sort order.

Check if the array is sorted in descending order (loosely). Use Array.prototype.reverse() and Array.prototype.findIndex() to find the appropriate last index where the element should be inserted.

const sortedLastIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el));
  return index === -1 ? 0 : arr.length - index;
};

Examples

sortedLastIndex([10, 20, 30, 30, 40], 30); // 4


⬆ Back to top

sor

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文