How to identify duplicate values in a JavaScript array

Is there a way to check for duplicate values in an array and display an alert if any duplicates are found? Here is the function that attempts to do this:

function checkDuplicateTenure(){
    var f = document.frmPL0002;
    var supplgrid = document.getElementById("mdrPymtGrid2");  
    var len = (supplgrid.rows.length) - 1;

    for(var i=0;i<len;i++){
        if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
            alert("DUPLICATE LOAN TENURE IN MONTH(S)");
        }
    }

    return false;
}

This function successfully detects duplicate values in the array, but it encounters a JavaScript error when all values are different. The error message reads:

if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
Unable to get property 'value' of undefined or null reference.

Thank you!

Answer №1

We have identified a common out of bounds error in the code. To resolve this issue, consider implementing the following fix:

for (var i = 0; i < len - 1; i++) {

By making this adjustment, you can ensure that i+1 will always be within the bounds of the variable len.

Answer №2

modify it

for(let x=0;x<length-1;x++){
        if (f.arr_loanTerm[x+1].value == f.arr_loanTerm[x].value) {
            alert("DUPLICATE LOAN TERM IN MONTH(S)");
        }
    }

If your loop is executed 5 times and you set x+1 inside the loop, it will reach 6 which is an undefined index causing a JavaScript error.

Answer №3

Here's a suggestion for you to try out:

function findDuplicateTenure(){
    var form = document.forms.formPL0002;
    var grid = document.getElementById("paymentGrid");
    var length = (grid.rows.length) - 1;

    for(var index=0; index<length-1; index++){
        if (form.selectLoanTerm[index+1].value == form.selectLoanTerm[index].value) {
            alert("FOUND DUPLICATE LOAN TERMS IN MONTH(S)");
        }
    }

    return false;
}

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

When leaving the page, onBeforeUnload function aborts any ongoing HTTP requests

When attempting to send an http request using the fetch API upon leaving the page, I am encountering a blockage of the request. Is there a solution to this issue without resorting to using an async function or waiting for the request to complete, which tri ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

Tips on sorting objects by comparing them to array elements

I have an array called myarrays and an object named obj. I need to filter the object by comparing the elements of the array with the keys of the object. If you want to see the code in action, you can check it out on StackBlitz: https://stackblitz.com/edit ...

As I attempt to connect with the bitcoin average server, I encounter a 403 status code error in the communication

const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/inde ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Implementing specific CSS styles for images that exceed a certain size limit

Currently, I am facing a dilemma as I work on developing a basic iPhone website that serves as a port for my blog. The main issue I am encountering is the need to add a border around images above a specific size and center them in order for the blog to hav ...

Exploring the concept of module patterns in JavaScript

Currently, I am working on honing my JavaScript skills as I am relatively new to the language. I am attempting to identify the specific element that triggered an event and display it within a span element. However, I seem to encounter an issue as clicking ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

Trouble with unproductive downtime in ReactJS and JavaScript

I'm looking for a way to detect idle time and display a dialog automatically after a certain period of inactivity. The dialog should prompt the user to click a button to keep their session active. Currently, when the user clicks the button it doesn&a ...

Ways to create interactive multiple dropdown menu using vue-multiselect

I'm not sure if it's possible to achieve what I want with Vue for a specific component by changing its data and automatically loading it. Below is my expectation (tried in jQuery) var data = {country:{type:'dropdown',values:[' ...

Is it possible to execute this html-minifier through the terminal on Ubuntu?

I am encountering an issue while attempting to use this HTML minifier tool on Ubuntu via the command line. Every time I try to execute it, an error pops up. NodeJS and NPM installations go smoothly: root$ apt-get install -y nodejs npm Reading package lis ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

React: Eliminate the reliance on two interconnected contexts by implementing a globally accessible constant object

Working on a new significant update for react-xarrows, I encountered a complex situation that needs resolution. To help explain, let's visualize with an example - two draggable boxes connected by an arrow within a wrapping context. https://i.sstatic ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...

Does JavaScript array filtering and mapping result in a comma between each entry in the array?

The code snippet above showcases a function that retrieves data from a JSON array and appends it onto a webpage inside table elements. //define a function to fetch process status and set icon URL function setServerProcessesServer1761() { var url = "Serv ...

Attempting to extract information from an array of strings containing the URL of an API

I am looking to extract data from an array that contains APIs, but the issue is that the number of APIs in the array varies. For example, some arrays may have 3 API addresses while others have just 2. { "name": "CR90 corvette", "m ...

What causes the toggle effect in my jQuery onclick function to alternate between on and off when the initialization is repeated multiple times?

I am facing an issue with my website where icons/buttons trigger a menu when clicked. I need to load more data by adding more buttons, so I tried re-initializing the existing buttons using a jQuery onclick function whenever the number of buttons changes. ...

How can I generate two directory-based slider instances?

Update: Finally, I discovered the root of the problem within my stylesheet. Despite both sliders being loaded, they were overlapping due to their positioning, causing the second slider (or any additional ones) to remain hidden. I've been striving to ...

ASP.NET sending an AJAX request

Hi, I am new to the world of ajax requests and asp.net. I am facing an issue while sending an ajax request to an aspx page. Even though the server side debugging seems fine, I am encountering an error message in the response. I have already tried changing ...