> For the complete documentation index, see [llms.txt](https://jscula.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jscula.gitbook.io/docs/manipulation/.reduce.md).

# .reduce()

Reduces a Collection into a single value

```javascript
const total = $('.price*').reduce((sum, price) => {
  return sum + Number(price.text());
}, 0);
```

### Use cases

Use `.reduce()` when a collection needs one accumulated result:

* Calculate totals from values in matching elements.
* Build an object indexed by an element attribute.
* Combine text from several elements into one string.

### More examples

Index elements by their `data-id` attribute:

```javascript
const usersById = $('.user*').reduce((users, user) => {
  users[user.attr('data-id')] = user.text();
  return users;
}, {});
```

Combine tag labels into a comma-separated string:

```javascript
const labels = $('.tag*').reduce((result, tag, index) => {
  return index === 0 ? tag.text() : `${result}, ${tag.text()}`;
}, '');
```
