0

I am trying to make a website where you can "buy" books. (It is just a mock project) There is a catalog where you see the books and you can add them to a shopping cart.

On the catalog side, the books are stored in a books array.

books =[{
 "name":"bible",
 "author": "god"},
{
 "name":"javascript",
 "author": "web"}];

When the button "add to the shopping cart" is clicked a function is called with the specific book name(e.g. bible). Then the book is added to the shopping cart array. shoppingCart =[];

Before the values are added to the shopping cart array I want to check if a book with the same name already exists in the shopping cart. If yes a counter should just count +1. If not the whole book should be added.

I do not understand how to check if a value already exists in an array. I tried to check with

addToShoppingCart(name) {
   this.shoppingCart.name.indexOf(name),
   this.shoppingCart.indexOf(name),
   this.shoppingCart.includes(name),
   this.shoppingCart.name.inclueds(name)}

but nothing of that did work. Can anyone please help me with that task?

4
  • 1
    includest method of array Commented Jan 14, 2021 at 19:47
  • 1
    this.shoppingCart.find(item => item.name === name) !== undefined Commented Jan 14, 2021 at 19:49
  • let isExist = !!this.shoppingCart.filter( b => b.name === name).length Commented Jan 14, 2021 at 19:50
  • this.shoppoingCart.some(item => item.name === name) id this returns true: counter = counter+1 Commented Jan 14, 2021 at 19:52

2 Answers 2

2

Use the Array.find() method along with the object property value you wish to test.

books =[{
 "name":"bible",
 "author": "god"},
{
 "name":"javascript",
 "author": "web"}];
 
function testCart(name){
 return books.find(item => item.name === name) !== undefined
}
 
console.log(testCart("Bible"));
console.log(testCart("bible"));

Sign up to request clarification or add additional context in comments.

6 Comments

I tried your answer and it works. I am just wondering why true and false is returned and not the name. It makes sense because for further processing true and false is better to use. But in the documentation, it says "The find() method returns the value of the first element in the provided array that satisfies the provided testing function." --> So why true and false when the VALUE of the first element should be returned?
@SNnaKR You're right that .find() returns the value of the first element found, but because !== undefined follows it, the expression is turned into a conditional statement and conditional statements only return Boolean answers. So, whatever value is returned from .find() is tested to see if it is not undefined, which means that something was found.
@ScottMarcus could you please reply to my comment? I do not understand what's wrong with using Array.some but I have got negative votes. If it's wrong to use I would like to avoid it in my code.
@SNnaKR precisely what Scott said, that's why I edited my answer below, since some returns a boolean directly, while .find returns the object itself. That's why find is useful when you want to further process the object.
@DiegoRodriguez I didn't say anything was wrong with .some(). It was your original answer that I commented on. .some() does the job! ;)
|
-1

There are several ways. The most succinct one—and legible—might be using Array.some:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

const books = [
  {
    "name":"bible",
    "author": "god"
  },
  {
    "name":"javascript",
    "author": "web"
  }
];

const isInShoppingCart = (query) => books.some(book => book.name === query);

const query = 'Bible';
console.log(`Is the book "${query}" included? > ${isInShoppingCart(query)}`);

const correctQuery = query.toLowerCase();
console.log(`Is the book "${correctQuery}" included? > ${isInShoppingCart(correctQuery)}`);

6 Comments

If all you need to know is if the book is already in the object array, .map() wouldn't be optimal because it creates another array. .forEach() would be more appropriate.
The "optimal" definition varies by use-case. A functional approach might be better depending on what he is trying to accomplish. Yet, as I said, there are many ways. forEach or even filter / reduce, in case you want to immediately add the filtered result to another place. Optimizing prematurely will not help.
The "optimal" definition varies by use-case. <-- Right, and the OP has stated what the use case is here and .map() isn't optimal.
How would you do it in a succinct way? (Without if or creating auxiliary variables). I was thinking of this: ``` let found = false; books.forEach(book => { if(book['name'] === query) found = true } ); if(found) console.log('FOUND'); ``` But, as you can see, it is not short.
How would you do it in a succinct way? Without if and creating auxiliary variables. <-- Why must I do it without if or auxiliary variables? Where did that requirement come from? Who's optimizing now? Did you look at my answer BTW?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.