Aller au contenu principal

concat()

concat<T>(array, ...values): T[]

Concatenates arrays and values into a new array.

DEPRECATED

Use array.concat() directly instead.

Reason:
Native equivalent method now available


Type Parameters

T: T

The type of elements in the arrays.


Parameters

array: T[]

The initial array.

values: ...(T | T[])[]

Additional arrays or values to concatenate.


Returns: T[]

A new array containing all elements from the input arrays.


See Also


Since

2.0.0


Also known as

appendAll (Effect) · concat (Lodash, es-toolkit, Remeda, Ramda) · mergeArrayable (Antfu) · ❌ (Radashi, Modern Dash)


Example

const arr1 = [1, 2];
const arr2 = [3, 4];

// ❌ Deprecated approach
const concatenated = concat(arr1, arr2);
console.log(concatenated); // [1, 2, 3, 4]

// ✅ Recommended approach
const concatenatedNative = arr1.concat(arr2);
console.log(concatenatedNative); // [1, 2, 3, 4]

How it works?

Creates a new array concatenating arrays/values. Deprecated: Use array.concat() or spread operator directly.

Native Equivalent

// ❌ concat(arr, 2, [3])
// ✅ arr.concat(2, [3])
// ✅ [...arr, 2, ...other]

Use Cases

Merge multiple data sources 📌

Combine arrays from different sources into a single collection.

const local = [{ id: 1 }];
const remote = [{ id: 2 }, { id: 3 }];
local.concat(remote);
// => [{ id: 1 }, { id: 2 }, { id: 3 }]

Append new items to list immutably

Add new items without mutation.

const todos = [{ id: 1, text: "Buy groceries" }];
const newTodo = { id: 2, text: "Walk the dog" };
todos.concat([newTodo]);

Prepend default options to user choices

Add default options at the beginning of a list.

const defaultOption = [{ value: "", label: "Select..." }];
const countries = [{ value: "us", label: "USA" }];
defaultOption.concat(countries);