Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have:

 onCheckRecipe(e) {
    if (e.detail.checked === true) {
      let tickedRecipe = e.detail.value;
      let foundRecipeIngredients = [];
      let foundRecipe;
      this.loadedRecipes.filter(function (el) {
        if (el._id === tickedRecipe) {
          el.ingredients.map((elm) => {
            foundRecipe = elm;
            foundRecipeIngredients.push(foundRecipe);
          });
        }
      });
      this.groceryListUpdated = foundRecipeIngredients;
      this.groceryListDefault = this.groceryListDefault.concat(
        this.groceryListUpdated
      );
    }
  }

In the console, I see something like this:

(12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "", quantity: ""}
1: {_id: "5f64ac1eb227fea1f63a5ca3", name: "avocado", quantity: "50g"}
2: {_id: "5f64ac1eb227fea1f63a5ca4", name: "lemon juice", quantity: "5g"}
3: {_id: "5f64ac1eb227fea1f63a5ca5", name: "small mozzarella pearls", quantity: "70g"}
4: {_id: "5f64ac1eb227fea1f63a5c9e", name: "almond flour", quantity: "10g"}
5: {_id: "5f64ac1eb227fea1f63a5c9f", name: "egg", quantity: "10g"}
6: {_id: "5f64ac1eb227fea1f63a5ca0", name: "unsalted butter", quantity: "30g"}
7: {_id: "5f64ac1eb227fea1f63a5ca1", name: "peanut butter", quantity: "50g"}
8: {_id: "5f64ac1eb227fea1f63a5c99", name: "chia seeds", quantity: "10g"}
9: {_id: "5f64ac1eb227fea1f63a5c9a", name: "cherries", quantity: "15g"}
10: {_id: "5f64ac1eb227fea1f63a5c9b", name: "honey", quantity: "30g"}
11: {_id: "5f64ac1eb227fea1f63a5c9c", name: "almond flour", quantity: "10g"}
length: 12
__proto__: Array(0)

My goal is to avoid adding something like "almond flour" twice if it already exists in the array, and only update the quantity. I've tried various methods without success. Any insights or ideas would be greatly appreciated. Thank you.

Answer №1

To start, make sure to validate if the item exists in the list by using the findIndex method. If it does, proceed with a map operation and only update the quantity for that specific index.

If the item is not found, simply add it to the list using the concat function.

Here is an example code snippet provided below. You may need to customize it based on your requirements, but the core logic remains the same.

const items = [{
  _id: "1",
  name: "avocado",
  quantity: 50
}, {
  _id: "2",
  name: "pasta",
  quantity: 60
}]

function addItems(newItem) {
  const index = items.findIndex((curItem) => curItem.name === newItem.name);
  if (index >= 0) {
    return items.map((curItem, curIndex) => {
      return index === curIndex ? {
          ...curItem,
          quantity: curItem.quantity + newItem.quantity
        } :
        curItem;
    });
  } else {
    return items.concat(newItem);
  }
}

console.log('Current items', items);

console.log('Adding a known item', addItems({
  _id: "1232",
  name: "avocado",
  quantity: 50
}));

console.log('Adding a new item', addItems({
  _id: "23232332",
  name: "meat",
  quantity: 50
}));

Answer №2

I found exactly what I was looking for

checkRecipe(event) {
    if (event.details.checked === true) {
      for (let rec of this.recipesList) {
        if (rec.title === event.details.value) {
          rec.ingredients.forEach((ingred) => {
            let matchedIngredient = this.shoppingList.find(function (foundIngred) {
              return foundIngred.title === ingred.title;
            });
            if (matchedIngredient) {
                matchedIngredient.amount = matchedIngredient.amount + ingred.amount;
            } else {
              this.shoppingList.push(ingred);
            }
          });
        }
      }
 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the variable using Ajax after the content has loaded

I am struggling with the following code snippet: <?php $num=12; ?> <html> <head></head> <body> <div id="test"></div> <script type="text/javascript"> function fetchContent() { var ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

Incorporate the feedback received from the user in the previous trial as a prompt for the next

I am currently working on developing an experiment using the JSPsych JavaScript package. The main goal of my experiment is for participants to input a letter in a survey-text trial, and then have that same letter presented back to them as a stimulus in the ...

Event handler for "copy" on the iPad

Is it possible to bind an event handler to the copy event on iPad or iPhone devices? ...

Ways to minimize an array of objects by shared key values?

Suppose I have an array of objects structured like this: var jsonData = [ {"DS01":123,"DS02":88888,"DS03":1,"DS04":2,"DS05":3,"DS06":666}, {"DS01":123,"DS02":88888,"DS03":2,"DS04":3,"DS05":4,"DS06":666}, {"DS01":124,"DS02":99999,"DS03":3,"DS04" ...

The functionality of changing the source to the "docs" folder is not supported

I'm currently working through a tutorial on deploying to GitHub Pages. You can find the tutorial here. Based on my understanding of the following command: ng build --prod --output-path docs --base-href /<project_name>/ I am using the Angular ...

How come TypeScript does not generate an error when attempting to import a default export that does not exist?

As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x instead of import x: The original snippet looked like this: const ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Specialized Node.js extension for automatic dependency installation

My current setup involves a custom Yeoman generator for specific applications, which comes with its own set of dependencies and configurations. - GruntJS must be installed globally; - Bower must be installed globally; - Yeoman must be installed globally ...

EJS: Dynamically linking CSS and JS files according to specific page conditions

Is there a way to conditionally call CSS/JS files based on specific page conditions in EJS? Can we use a flag from the router or base it on the URL in the EJS file? Note: The code below works perfectly when accessing the /editor page, but it will cause er ...

iOS app launch does not trigger Phonegap handleOpenURL

Receiving an alert message when the app is open in the background. However, when I close the app from the background and then relaunch it, the alert message doesn't appear. The handleOpenURL function cannot be invoked in JavaScript when the app is lau ...

Comparing arrays in IOS with varying values and lengths: a step-by-step guide

I need help comparing two arrays. Array A contains 4 elements and array B contains 10 elements. I want to determine if any values in array A are also present in array B. Below are the codes I am using for this comparison. for(int i = 0; i <= deepsi ...

Storing Angular 4 Http Post response data in an object

I'm currently working with Angular 4 in conjunction with an Asp.net web API. I am facing difficulties in reading the properties of my response. This is how my response appears: https://i.stack.imgur.com/NDJCo.png Here is my post request: postLogi ...

I'm encountering a type error every time I attempt to render an EJS page. Could someone please take a look and help me troubleshoot?

Below is the index.js code: CODE HERE const express = require('express'); const app = express(); const path = require('path'); app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(ex ...

What is the best way to display just one record that has the lowest score out of all the records?

I need help with displaying only 1 record from the DL list that has the lowest score, instead of showing all records. In the example on stackblitz, you can see that for the first record, the DL scores are: 54, 20, and updated. Instead of displaying all 3 ...

Exchange the memory addresses of two arrays within a function

Currently, I am working on a mergesort implementation but without the traditional copy step into an extra temp array. To facilitate this process, I have introduced an auxiliary array called aux. int * aux; aux = (int *) calloc(n, sizeof(int)); The variab ...

Does npm run use a separate version of TSC?

I am encountering an issue with my VS Code and Node.js project that uses Typescript. Within my package.json file's script block, there is an entry: "build-ts": "tsc" When I run simply tsc on the integrated terminal command line, the compilation proc ...

Each element is being adorned with the Ajax success function class

Currently, I am in the process of creating an Ajax function to integrate search features into my project. The search function itself is functioning properly; however, within the success: function, I am encountering an issue. Specifically, I am attempting t ...

Automated configuration of AWS Amplify JavaScript using Gitpod

Looking to streamline the setup process for an AWS Amplify JavaScript project on Gitpod. My goal is to eliminate the manual steps of configuring the amplify-cli, such as adding IAM users and generating the aws-exports.js file. Successfully installed the a ...

How to eliminate arrows in ngx-bootstrap datepicker?

I recently started working with Angular and Bootstrap and I'm facing an issue. I am using a ngx bootstrap datepicker, but I would like to remove the standard arrows on the buttons of the datepicker calendar. Here is a screenshot of the problem: https ...