Locate the initial occurrence of a duplicated element within an array

I need to check for duplicate values in an array element. Within my array, I have multiple objects like {S:1,R:2,V:3}. My goal is to display an alert message if there are duplicate values for the "S" element in that array.

My Approach:

var arr=[{S:1,R:2,V:3},{S:2,R:2,V:3},{S:1,R:4,V:5},{S:3,R:2,V:3}, 
         {S:2,R:2,V:3},{S:3,R:4,V:5}];
function findDuplicate()
{
var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1].S == sorted_arr[i].S) {
        results.push(sorted_arr[i]);
         break;
    }
}

   console.log(results);
   return results;
}

if(findDuplicate().length==1)
{
alert("S -" + findDuplicate()[0].S +" is a duplicate");
}

However, the code snippet above (referencing this answer) is not yielding the desired outcome. I am expecting an alert message stating S - 1 is a duplicate.

Answer №1

Modify your loop structure to achieve the task using nested loops instead of a single loop.

var arr=[{S:1,R:2,V:3},{S:2,R:2,V:3},{S:1,R:4,V:5},{S:3,R:2,V:3}, 
         {S:2,R:2,V:3},{S:3,R:4,V:5}];
function duplicateValidation()
{
    var sorted_arr = arr.slice().sort();
    var results = [];
    for (var i = 0; i < sorted_arr.length - 1; i++) {
    var S_type = sorted_arr[i].S;
    for (var j = i; j < sorted_arr.length - 1; j++){
        if (sorted_arr[j + 1].S == S_type) {
            results.push(sorted_arr[i]);
            break;
        }
    }
 }       
   return results;
}

if(duplicateValidation().length > 1)
{
console.log("S - " + duplicateValidation()[0].S +" is duplicate");
}

Answer №2

Sorting the array may seem like an unnecessary step - why not avoid the extra iteration and check for duplicates in a more efficient way? By simply iterating through the array once, you can easily identify any duplicate values without the need for sorting.

One approach is to loop through the array, checking each item's value of "S" and determining if it has already been added to a results array. If a duplicate is found, store the index of the duplicated item in a separate duplicates array. This way, you can quickly pinpoint the indexes of all duplicate items within the array.

var arr=[{S:1,R:2,V:3},{S:2,R:2,V:3},{S:1,R:4,V:5},{S:3,R:2,V:3}, 
         {S:2,R:2,V:3},{S:3,R:4,V:5}];

var results = [];
var duplicates = [];
arr.forEach(function(obj, index){
  results.indexOf(obj.S) == -1
  ? results.push(obj.S)
  : duplicates.push(index)
})

var duplicatesLength = duplicates.length;
duplicates.length > 0
 ? console.log(duplicatesLength + ' duplicates found at index (' + duplicates.join(', ')+')')
 : console.log('No duplicates found')

//outputs: 3 duplicates found at index (2, 4, 5)
// meaning that item 0 matches item 2, item 1 matches item 4, and item 3 matches item 5

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

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Transmit a JSON array from a controller to a JavaScript variable

I have retrieved a JSON array from a database and it is set up in a controller like this: public ActionResult highlight() { var statesHighlight = db.Jobs .Select(r => r.State); return Json(statesHighlight , JsonRequestBehavi ...

Incorporating two perspectives and exchanging information within AngularJS

Trying to establish real-time data sharing between two separate views across different machines can be a challenging task. One view must control the other, such as updating a counter in one view and displaying the result in another. The goal is to have the ...

Navigating with Next.js Router: Dynamic URLs and the power of the back button

Utilizing the Router from the package next/router allows for a dynamic URL and loading of different content on the page: Router.push('/contract', `/contract/${id}`); An issue arises where the back button does not function as expected after runni ...

Transform a TensorFlow dataset comprising of input data and corresponding labels into two separate NumPy arrays

Working with Tensorflow 2.9.1 requires handling a test_dataset object of the class tf.data.Dataset. This object contains both inputs and labels, with inputs being 4-dimensional Tensors and labels being 3-dimensional Tensors: print(tf.data.Dataset) <Pref ...

"Successful implementation of Ajax function in local environment but encountering issues when running online

I am facing an issue with my AJAX function. It works perfectly fine on my local server but does not return anything when I move it to my online server. Below is the code snippet: This is the part of the page where I call the showEspece() function: echo ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...

Leveraging jQuery for Crafting a Quiz with True or False Questions

Exploring the most effective approach to constructing a questionnaire. Find images below for reference. The current code setup is functional but becomes lengthy after just two questions. How can I streamline this code to minimize repetition? // prevent d ...

Combining multiple arrays dynamically in Julia

If I have a variable number of 2D arrays that I want to merge into a 3D array: n = 10 # Number of arrays, can be any positive integer arrays = Dict() for i in 1:n arrays[i] = rand(2,2) end The standard syntax for merging arrays is: cat(arr1, arr2, ...

The integration of react-color Saturation with @types/react-color is currently unavailable

In my quest to develop a customized color picker, I am utilizing the react-color library (^2.19.3) together with @types/react-color (^3.0.4). The issue arises when trying to import the Saturation component since it is not exported from the types in the ind ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

Observing the tendencies of count array

In the "count" char array, only characters are stored. count[str.charAt(i)]++; What is happening in the above line exactly? count[str.charAt(i)] == 1 How can an integer be compared with a char since "count" is a char array? The code below is pasted in ...

How can I display data saved from step 2 in a multi-step form with 4 steps, when I return from step 3 to step 2?

Let's consider this scenario: Imagine the user is at step 2 and types their name into <input type="text" class="form-control input-xl" ngModel name="firstName"> They proceed to step 3 but then decide to return to step 2. The information entere ...

A class or another interface is the only type that an interface is allowed to extend

We are currently using typescript version 2.9.2 I encountered an issue while trying to extend the interface DropDownOption. I received the error "error TS2312: An interface may only extend a class or another interface." Is there an alternate approach to ...

The issue of Rails 4 serving JavaScript as plain text instead of executing it when attempting to utilize AJAX

I am in the process of constructing a basic page layout featuring two side-by-side columns. The left column is intended for user input via a form submission. Upon submitting the form, I want the right column to dynamically update (using AJAX) and display a ...

Demonstrate the utilization of JQuery to unveil a secondary menu

I need assistance in implementing a sub-menu that automatically appears within 2 seconds after the page loads, instead of requiring user interaction. I am currently utilizing JQuery, which serves as the core framework for my website. It is crucial for this ...

I'm currently working on a React toaster component, but I'm facing an issue where it's not displaying

I have created the Toaster component programmatically and I am passing the message through another component. This is how my Toaster component looks: export default class MyToaster extends React.Component { constructor(props) { super(props); ...

Iframe navigation tracking technology

Let's say I have an iframe element in my HTML document. <html> <body> This is my webpage <button> Button </button> <iframe src="www.example.com"></iframe> </body> </html> If a user clicks on links wi ...

What is the best way to transform a string array into a number array?

I'm attempting to convert a string array into a number array and after conducting some research online, I came across this solution: let numbersAsStringArray = originalQueryParams[property] ?? [] let numbers = numbersAsStringArray.map((i) => ...