How can I verify if the content array in local storage in JavaScript has duplicate values

Is there a way to prevent duplicate entries in an array of doubles like [1, 2, 2, 3, 1] when checking its contents?

function checkDuplicates() {
    entered_values = document.getElementById('values').value;
    values_array = entered_values.split(',');

    if($.trim(entered_values) != ''){
        //location.href = base_url + 'values/' + encodeURIComponent(entered_values);
    }
    if (localStorage.data_list){
        data_list = JSON.parse(localStorage.getItem('data_list'));
        $("#history").toggle();
    } else {
        data_list = [];
    }
       
    for (num in values_array){
        console.log(localStorage.data_list);
        data_list.push({'numbers':values_array[num]});
        localStorage.setItem('data_list', JSON.stringify(data_list));
    }
}

Answer №1

If you want to check for duplicate values and add them to an array, you can utilize Array.prototype.includes():

for (i in results){
  console.log(localStorage.data_list);
  if(!data_list.includes(results[i])){ 
      data_list.push({'result':results[i]}); 
  }
}
localStorage.setItem('data_list', JSON.stringify(data_list));

Answer №2

Another option is to utilize the indexOf method like this: Array.prototype.indexOf(el). In this case, 'el' represents the element being searched for. The indexOf method will return the index of the element in the array, or -1 if it is not found.

for (x in resi){
   if(daftar_data.indexOf(resi[x]) > -1) {
      daftar_data.push({'resis':resi[x]});
   }
}
localStorage.setItem('daftar_data', JSON.stringify(daftar_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

Utilizing loops in R to append new rows to a dataframe

I am trying to enhance my dataframe by adding extra rows using a loop. The loop will cycle through a list of API endpoints, with each iteration delivering a single row of data. However, I am struggling to figure out how to add additional rows in a way th ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

Latest output is fetched by jQuery from the load() method

I'm encountering an issue with the code present in index.html: $(document).ready(function() { $('#generate').click(function() { //$("#results").empty(); $("#results").html(""); $("#results").load("generate.php"); }); }); In addition ...

Elevate the value within a function and refresh the said function

I'm currently facing a challenge with this particular piece of code, let spin = new TimelineMax(); spin.to($('.particle'), 150, { rotation: 360, repeat: -1, transformOrigin: '50% 50%', ease: Linear.easeNone }); Th ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

The three.js animation fails to load on Github Pages

I have encountered an issue with my website. It runs smoothly when I use "parcel index.html" locally, but once I post it to Github pages, the JavaScript animation does not display. Upon checking the browser console, I see no errors. Can anyone provide guid ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...

What might be causing the in-viewport javascript to not work in my code?

Why is my in-viewport JavaScript code not functioning properly? Link to JSFiddle code When the Click to move button is clicked, the cat image will slide correctly. However, when implementing the following code: if($("#testtest").is(":in-viewport")) ...

JavaScript libraries are not required when using the .append function to add HTML elements

Currently, I am attempting to utilize $.ajax in order to retrieve an html string from a php file and append it to the current html div. Oddly enough, when I use php echo, everything functions properly. However, when I attempt to load dynamically using $.lo ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

Convert an array of strings to my custom array type in Angular

I have a list of different statuses Here is an example of it: export enum InvoiceStatus { Created = 1, Pending = 2, Approved = 3, Rejected = 4, Paid = 5, Deleted = 6, PreparingPayment = 7 } My goal is to convert it into an ar ...

"Enhance Your Form with JQuery Date Selector for Multiple Input

Using JQuery and ASP.Net C#3.0. Here is the script I am working with: <script> $(document).ready(function () { $("[id$=txtHiddenDate]").datepicker({ showOn: "button", buttonImage: "../../images/calendar-icon.gif", ...

Using JavaScript to sort through JSON data arrays

I am dealing with a JSON data structure as shown below: var data = [ { "type": "Feature", "id": 1, "properties": { "name": "William", "categorie": 107, "laporan":"Fire", "time":1, ...

Using the Link component in Next.js ensures that the useEffect hook runs only once

When navigating between pages, I utilize the Link component to open them without reloading: <Link href="/home"><a>Home</a></Link> <Link href="/page"><a>Page</a></Link> In my home page cod ...

Move the absolute div by sliding it to the left from 120% to -10px

I want to move an absolute positioned div from the left side of the screen to -10px on button click. Here's my attempt so far, but it's not working as expected. Javascript/jQuery $('.button').click(function() { $(this).parent().f ...

Display content in a div after the page is fully loaded with either a placeholder or animated loading

Hello everyone, this is my first post on here. I am relatively new to PHP, so any help or advice would be greatly appreciated. ...

Tips for highlighting text in a textarea using jQuery or JavaScript

I'm intrigued by Facebook's functionality. They utilize textareas in their comments and status sections, but whenever I tag someone in a post, the selected text is highlighted with a light blue background within the textarea. As far as I know, th ...

Utilizing setTimeout within every iteration is ineffective

A vast gallery containing around 400 pictures is featured on my website. I have implemented a button that allows users to delete all images from both the DOM and the server through an AJAX request for each file. While testing, I attempted to use the setTi ...

Display and conceal HTML content using the value of AngularJS

I am looking to toggle the visibility of a <button> element on my HTML page based on the value of a directive {{auth?.loggedIn}} from AngularJS, whether it is true or false. This is how my HTML currently looks: <button (click)="onLogin()&quo ...