Skip to main content

each()

each<T>(collection, iteratee): T[]

each<T>(collection, iteratee): T

Iterates over elements of collection and invokes iteratee for each element.

DEPRECATED

Use array.forEach() or for...of loop directly instead.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array, or the object type.


Parametersโ€‹

Overload 1:

collection: T[]โ€‹

The collection to iterate over.

iteratee: (value, index, array) => voidโ€‹

The function invoked per iteration.

Overload 2:

collection: Tโ€‹

The collection to iterate over.

iteratee: (value, key, object) => voidโ€‹

The function invoked per iteration.


Returns: T[]โ€‹

The original collection.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

forEach (Lodash, es-toolkit, Remeda, Ramda, Effect) ยท โŒ (Radashi, Modern Dash, Antfu)


Exampleโ€‹

const numbers = [1, 2, 3, 4, 5];

// โŒ Deprecated approach
each(numbers, (value, index) => {
console.log(`Index ${index}: ${value}`);
});

// โœ… Recommended approach (for arrays)
numbers.forEach((value, index) => {
console.log(`Index ${index}: ${value}`);
});

// โœ… Alternative with for...of
for (const [index, value] of numbers.entries()) {
console.log(`Index ${index}: ${value}`);
}

// โœ… Recommended approach (for objects)
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

How it works?โ€‹

Iterates over elements of collection. Deprecated: Use array.forEach() directly.

Native Equivalentโ€‹

// โŒ each(arr, fn)
// โœ… arr.forEach(fn)

Use Casesโ€‹

Iterate over items for side effects ๐Ÿ“Œโ€‹

Execute a function for each element for logging or analytics.

const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
users.forEach(user => console.log(`Processing: ${user.name}`));

Traverse object propertiesโ€‹

Iterate over all properties of an object.

const config = { apiUrl: "https://api.com", timeout: 5000 };
Object.entries(config).forEach(([key, value]) => {
if (value === undefined) console.warn(`${key} is undefined`);
});

Process form fieldsโ€‹

Iterate over elements for bulk operations.

const fields = document.querySelectorAll("input");
[...fields].forEach(field => field.value = "");