@antoniovdlc/reduce
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

reduce

version issues downloads license

Custom reduce functions.

Installation

This package is distributed via npm:

npm install @antoniovdlc/reduce

Motivation

Reducing arrays to a single value is a common operation in JavaScript. This library abstracts away some of the most common reduce operations.

Usage

You can use this library either as an ES module or a CommonJS package:

import { sum, average, groupBy } from "@antoniovdlc/reduce";

- or -

const { sum, average, groupBy } = require("@antoniovdlc/reduce");

Examples

All reduce functions can be used out of the box for computing single values as follows:

import { sum } from "@antoniovdlc/reduce";

const arr = [1, 2, 2, 13, 20, 4];
arr.reduce(sum); // 42

All reduce functions provide a .on("key") function which allows to compute single values from arrays of objects by nested fields:

const arr = [
  { name: "Bob", age: 25 },
  { name: "Alice", age: 38 },
  { name: "Tom", age: 60 },
  { name: "Candice", age: 45 },
];
arr.reduce(average.on("age")); // 42

Note that if you are using TypeScript, you need to pass an initialization value: arr.reduce(average.on("age"), 0); // 42

Reduce functions

Here is a list of provided reduce functions:

sum

Computes the sum of all the elements in an array.

average

Computes the average of all the elements in an array.

groupBy

Generates an object from an array of objects, where the keys correspond to the values of the first argument, and the value corresponds to the object itself.

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i @antoniovdlc/reduce

Weekly Downloads

5

Version

1.0.0

License

MIT

Unpacked Size

7.24 kB

Total Files

6

Last publish

Collaborators

  • antoniovdlc