PHP's array_chunk in TypeScript

How to use

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

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

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_chunk(['Kevin', 'van', 'Zonneveld'], 2)[['Kevin', 'van'], ['Zonneveld']]
2array_chunk(['Kevin', 'van', 'Zonneveld'], 2, true)[{0:'Kevin', 1:'van'}, {2: 'Zonneveld'}]
3array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2)[['Kevin', 'van'], ['Zonneveld']]
4array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2, true)[{1: 'Kevin', 2: 'van'}, {3: 'Zonneveld'}]

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

  • Important note: Per the ECMAScript specification, objects may not always iterate in a predictable order

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

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

type ArrayChunkInput<T> = T[] | PhpAssoc<T>
type ArrayChunkOutput<T> = T[] | PhpAssoc<T>

export function array_chunk<T>(
input: ArrayChunkInput<T>,
size: number,
preserveKeys?: boolean,
): ArrayChunkOutput<T>[] | null {
// discuss at: https://locutus.io/php/array_chunk/
// original by: Carlos R. L. Rodrigues (https://www.jsfromhell.com)
// improved by: Brett Zamir (https://brett-zamir.me)
// note 1: Important note: Per the ECMAScript specification,
// note 1: objects may not always iterate in a predictable order
// example 1: array_chunk(['Kevin', 'van', 'Zonneveld'], 2)
// returns 1: [['Kevin', 'van'], ['Zonneveld']]
// example 2: array_chunk(['Kevin', 'van', 'Zonneveld'], 2, true)
// returns 2: [{0:'Kevin', 1:'van'}, {2: 'Zonneveld'}]
// example 3: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2)
// returns 3: [['Kevin', 'van'], ['Zonneveld']]
// example 4: array_chunk({1:'Kevin', 2:'van', 3:'Zonneveld'}, 2, true)
// returns 4: [{1: 'Kevin', 2: 'van'}, {3: 'Zonneveld'}]

if (size < 1) {
return null
}

const keepKeys = Boolean(preserveKeys)

if (Array.isArray(input)) {
if (keepKeys) {
const chunks: PhpAssoc<T>[] = []
for (const [i, value] of input.entries()) {
const chunkIndex = Math.floor(i / size)
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = {}
}
chunks[chunkIndex][String(i)] = value
}
return chunks
} else {
const chunks: T[][] = []
for (const [i, value] of input.entries()) {
const chunkIndex = Math.floor(i / size)
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = []
}
chunks[chunkIndex].push(value)
}
return chunks
}
} else {
const inputEntries = Object.entries(input)
if (keepKeys) {
const chunks: PhpAssoc<T>[] = []
for (const [i, [key, value]] of inputEntries.entries()) {
const chunkIndex = Math.floor(i / size)
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = {}
}
chunks[chunkIndex][key] = value
}
return chunks
} else {
const chunks: T[][] = []
for (const [i, [, value]] of inputEntries.entries()) {
const chunkIndex = Math.floor(i / size)
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = []
}
chunks[chunkIndex].push(value)
}
return chunks
}
}
}

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