PHP's array_reduce in TypeScript

How to use

Install via yarn add locutus and import: import { array_reduce } from 'locutus/php/array/array_reduce'.

Or with CommonJS: const { array_reduce } = require('locutus/php/array/array_reduce')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;})15

PHP arrays and TypeScript/JavaScript

Please note that Locutus uses TypeScript/JavaScript objects as substitutes for PHP arrays, they are the closest we can get to this hashtable-like data structure without rolling our own. While many TypeScript/JavaScript implementations preserve the order of object properties, the ECMAScript Language Specification explicitly states that:

The mechanics and order of enumerating the properties is not specified.

In practice most engines preserve insertion order, but if your code depends on key ordering across platforms, keep this caveat in mind.

To influence how Locutus treats objects as arrays, you can check out the locutus.objectsAsArrays setting.

Notes

  • Takes a function as an argument, not a function’s name

Here's what our current TypeScript equivalent to PHP's array_reduce looks like.

import type { PhpRuntimeValue } from '../_helpers/_phpTypes.ts'

export function array_reduce<TValue, TCarry>(
aInput: readonly TValue[],
callback: (carry: TCarry, value: TValue) => TCarry,
initial: TCarry,
): TCarry

export function array_reduce<TValue>(
aInput: readonly TValue[],
callback: (carry: TValue | null, value: TValue) => TValue,
): TValue | null

export function array_reduce(
aInput: readonly PhpRuntimeValue[],
callback: (carry: PhpRuntimeValue | null, value: PhpRuntimeValue) => PhpRuntimeValue,
initial?: PhpRuntimeValue,
): PhpRuntimeValue | null {
// discuss at: https://locutus.io/php/array_reduce/
// original by: Alfonso Jimenez (https://www.alfonsojimenez.com)
// note 1: Takes a function as an argument, not a function's name
// example 1: array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;})
// returns 1: 15

let carry: PhpRuntimeValue | null = typeof initial === 'undefined' ? null : initial
for (const value of aInput) {
carry = callback(carry, value)
}
return carry
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP array functions


Star