DEV Community

Dillon
Dillon

Posted on

MAP, MAP, MAP

.map

Let's Goooooooooo

Map can transform the array. It doesn't change or mutate the old one, it creates a new one.

you can do this really neat thing with arrays where you can utilize the .map feature to add only to those nested objects where a certain criteria is met, the ones that don't meet the criteria don't have any value added, not even to say that it is false.

say you have an array of books. Each book has a objects that have its title, author, and number of sales. from number of sales you know that if the total sales exceeded 100 (sales in thousands), it was a best seller.

here's the code that would allow you to add in the value if the object should have the best seller line added.

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 updatedBooks = books.map(book=> book.sales > 100 ? {...book, bestSeller: true} : book);cons

console.log(updatedBooks)

btws... you will have to add in quotes around the author and title values

.forEach()

This is powerful and lets us work off the arrays we have built.

Using the array we created above with the bestSeller value included, we can alert the user if the book was a best seller. We will demonstrate chaining here.

books.map(book=> book.sales > 100 ? {...book, bestSeller: true} : book).forEach(book => {
if (book.bestSeller) {
console.log(${book.title} written by ${book.author} was a best seller!!
}

})

Top comments (1)

Collapse
 
dillpap profile image
Dillon

If you want only a subset of the array, you can use the filter method.

using the

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},
{title: War and Peace, author: Tolstoy, sales: 789}
];

const authorName = books.filter(book=>book.author.startsWith("T"))

If you console.log authroName, you get back some the objects for Goldfinch and War and Peace.

You can chain the filters though...

const authorName = books.filter(book=>book.author.startsWith("T") && book.sales >=1000);

If you want just one, you can use the .find

const authorName = books.find(book=>book.author.includes("Tart") && book.sales >=1000);

.includes for string is case sensitive