Preventing duplicate arrays from being stored in localStorage by validating them

Is there a way to ensure that when the "add to favorites" button is clicked, its data is stored in localStorage only once? If it already exists in localStorage, clicking for a second time should not have any effect except showing an alert message.

I would like to achieve this functionality in Angular Ionic. Any suggestions on how to implement this?

Here is a link to my working application and sample code:

https://github.com/Novian227/WeatherAppIonic

save() {
  let data = [];
  let w = JSON.parse(localStorage.getItem('fav'));

  if (w != null) {
    for (let i=0; i<w.length; i++) {
      data.push(w[i]);
    }
  }

  data.push(this.weather);
  localStorage.setItem('fav', JSON.stringify(data));
}

Answer №1

UPDATE : It turns out that this.weather is actually an object and not a string.

If your array only consisted of simple data types like numbers or strings, using indexOf would have been sufficient. However, since your array contains objects, a different approach is needed.

Instead, you should utilize the findIndex method to determine if the object already exists in the array.

save() {
  let data    = JSON.parse(localStorage.getItem('fav')) || [],
      isExist = data.findIndex((obj) => {
        // Compare all keys here to ensure uniqueness
        // You can include multiple keys as needed
        return obj.date == this.weather.date && obj.temp == this.weather.temp; 
      }) != -1;

  if (isExist) {
    // display alert message here 
  } else {
    data.push(this.weather);
    localStorage.setItem('fav', JSON.stringify(data));
  }
}

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

Issue encountered while trying to insert a new row into the mat-table

I need help with inserting a new row in mat-table using a button. I wrote a function for this, but when I click the button, I encounter an error CalculatoryBookingsComponent.html:62 ERROR Error: Cannot find control with path: 'rows -> 0'. Addi ...

Generating distinct identifiers for WebSocket and net.Socket connections

I am looking to assign unique identifiers to Websockets and net.Sockets so that each client can be identified by the identifier attached to the socket when a message is received. Previous findings: For WebSocket: Based on my research on Stack Overflow a ...

Typescript: The .ts file does not recognize the definition of XMLHttpRequest

I have encountered an issue with a .ts file containing the following code: var xhttp = new XMLHttpRequest(); After running the grunt task to compile the ts files using typescript, no errors were reported. However, when I attempt to instantiate the class ...

Can you demonstrate how to showcase images stored in an object?

Is there a way to properly display an image from an object in React? I attempted to use the relative path, but it doesn't seem to be working as expected. Here is the output shown on the browser: ./images/avatars/image-maxblagun.png data.json " ...

Converting HTML to an array using Angular

Is there a way to convert HTML into an array of entities? For example: 'hi <em>there</em>' => ['hi', '<em>', 'there', '</em>'] ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Experiencing difficulties with managing immutable state within ngrx framework

Hi there, I'm currently exploring ngrx and trying to implement immutable state management. However, I've run into some issues with getting it to work properly. Below is the reducer I am working with: https://stackblitz.com/edit/brewbrut?file=src ...

Angular2 Interactive Modal Pop Up

Here is an example of a modal in HTML code: <app-modal #modal1> <div class="app-modal-header"> header </div> <div class="app-modal-body"> You c ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Oh no! A catastrophic NG_BUILD error has occurred: The mark-compacts are not working effectively due to an allocation failure near the heap limit. The JavaScript

While working on my Angular application, I keep encountering a JavaScript out of memory issue as indicated below: @bb-cli/bb-ang] ERR! NG_BUILD FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory I&apo ...

The Angular logout route appears to be neglected

I'm currently working on implementing a LogoutFunction, but I'm running into an issue where it's not being dispatched to my API (Spring Boot). The login functionality works perfectly fine. My goal is to pass an ID to the API and receive a su ...

The type of 'username' cannot be determined without specifying the reference to '@angular/forms/forms' in the node modules

I'm encountering an issue with my application: forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not po ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

Can someone point me to the typescript build option in Visual Studio 2019 Community edition?

When I created a blank node.js web app on VS 2015, there was an option under project properties called "TYPESCRIPT BUILD" that allowed me to configure settings like combining JavaScript output into a single file. After upgrading to VS 2019 Community, I ca ...

Alter the value by clicking a button within the DynamicRadioGroupModel in ng Dynamic Forms

I am working with ng-dynamic-form (version 6.0.4) and NG Bootstrap in Angular 6. I have a simple question. When a button click event is triggered, I want to change the value in DynamicRadioGroupModel by using the "setValue()" method. However, I am facing ...

Guide to generating a dropdown menu and linking it with data received from a server

I am completely new to Angular and recently received a project involving it. My task is to create a nested dropdown list for Json data retrieved from a server using Rest Api calls. The data contains a Level attribute that indicates the hierarchy level of ...

Personalize your Client-Id for Paypal

Currently integrating PayPal's Smart Payment Buttons into my Angular project. The index.html file contains the following script: <script src="https://www.paypal.com/sdk/js?client-id=MY_CLIENT_ID"> </script> I am working on developi ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

Updating an array of drag and drop elements in Angular Material

During my attempt to use drag and drop functionality with Angular Material, I encountered an issue with updating the `pos` key in a JSON array. Specifically, I wanted to set the `pos` value to the value of `event.currentIndex` while also adjusting the posi ...