DEV Community

MAP, MAP, MAP

Dillon on February 16, 2023

.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...
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