DEV Community

Dillon
Dillon

Posted on

REDUCE for Array

.reduce()

Reduce iterates over array elements. Reduce needs one additional argument.

books.reduce((accumulator, otherParam) => {
return accumulator;

}, 0); the 0 here is the starting point or what gets iterated over.

If we wanted to count up the number of books sold from among our array, we would have the following...

const books = [
{title: The Great Gatsby, author: Fitzgerald, sales: 2},
{title: Odyssey, author: Homer, sales: 1889},
{title: Hyacinth, author: Julien Linde, sales: 275},
{title: Goldfinch, author: Tart, sales: 1089}
];

const bookSales = books.reduce((accumulator, book) => {

return accumulator + book.sales;

}, 0);

console.log(bookSales)

Top comments (2)

Collapse
 
dillpap profile image
Dillon

.push versus unshift

.push adds an item to the end of an array, unshift

say you had a new book you wanted to add to the books array from above.

bestBook = [title: A woman first: first woman, author: President Selena Meyer, sales: 11222]

If you wanted to add President Meyer's book to the books array but in first position, you could do the following.

const completeBookList = [...bestBook, ...books]

If you wanted to return the first through the third books, you would do...

console.log(completeBookList.slice(0,4)

Collapse
 
dillpap profile image
Dillon

.push versus .concat

If you are trying to iterate off an existing array, you will end up changing the existing array, while creating the new array. This is because you are passing along a reference to the existing array.

Instead use the .concat.

.concat is called nonmutating. .push is mutating. Think of .concat as duplicating the old array and making a change to the duplicated array.

There is a cloning method

it would be...

const newBookList = [...books]

This clones the books array. With the cloned array, you are free to use something like the .push method.