In Javascript, set the index variable of the respected duplicate value to true in the array

I am seeking a solution for identifying duplicate values within an array of objects.

My goal is to set the value of a specific index variable to true if that index contains a duplicate value.

For example, consider the following array of objects:

let arr = [
        {
            name: 'abc',
            age: 20,
        },
    
        {
            name: 'xyz',
            age: 25,
        },
    
        {
            name: 'pqr',
            age: 22,
        },
    
        {
            name: 'abc',
            age: 27,
        },
    
        {
            name: 'abc',
            age: 26,
        },
    ]
    

In this case, indexes 3 and 4 have names that are duplicates of index 0. I would like to set the isError variable to true for indexes 3 and 4, and to false for the other indexes.

Any assistance on how to achieve this would be greatly appreciated.

Thank you.

Answer №1

Utilize a Set to keep track of existing names and then map through the array. Check if the name already exists in the Set, set the isError variable accordingly. Add the current name to the Set. Create a new object with the original data along with the isError property:

const checkForDuplicates = arr => {
  const storedNames = new Set();
  
  return arr.map(obj => {
    const isError = storedNames.has(obj.name)
    
    storedNames.add(obj.name)
    
    return { ...obj, isError };
  })
}

const sampleArray = [{"name":"abc","age":20},{"name":"xyz","age":25},{"name":"pqr","age":22},{"name":"abc","age":27},{"name":"abc","age":26}]

const result = checkForDuplicates(sampleArray)

console.log(result)

Answer №2

To start, organize the array and then apply the map function. Once the objects are sorted by name in ascending order, use the map function to create a new array. During this process, check if the current object's name matches the previous one. If it does, add a duplicate key and assign a value to it.

 if (index !== 0 && item.name == k[index - 1].name) {

This line skips checking the first object in the sorted array as there is no previous object to compare with. It evaluates if the name of the current object matches the name of the previous object using item.name == k[index - 1].name.

let arr = [{
    name: 'abc',
    age: 20,
  },

  {
    name: 'xyz',
    age: 25,
  },

  {
    name: 'pqr',
    age: 22,
  },

  {
    name: 'abc',
    age: 27,
  },

  {
    name: 'abc',
    age: 26,
  },
];
let k = arr.sort(function(a, b) {
  return a.name.localeCompare(b.name);
});
let z = k.map(function(item, index) {
  if (index !== 0 && item.name == k[index - 1].name) {
    return {
      name: item.name,
      age: item.age,
      duplicate: true
    }
  } else {
    return {
      name: item.name,
      age: item.age
    }
  }
});
console.log(z)

Answer №3

To track and manage data, consider using an object as a tracker by assigning a key using the name.

Iterate through the data, checking if the name already exists as a key in the op object. If it does, change the isError property of the current element to true. Otherwise, create a new key in op and set the isError of the current element to false.

let arr = [{name :'abc',age : 20,},{name :'xyz',age : 25,},{name :'pqr',age : 22,},{name :'abc',age : 27,},{name :'abc',age : 26,},]

let op = {}

arr.forEach( (inp,index) => {
  if( op[inp.name] ){
    inp.isError = true
  } else{
    inp.isError = false
    op[inp.name] = inp
  }
})

console.log(arr)

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 AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

Tips for customizing fonts in react-pdf

I am having difficulty in changing fonts within react-pdf. // Register Font Font.register({ family: "Roboto", src: "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf" }); The default f ...

What is the best way to use scrollIntoView() to display an additional item at the top or bottom of the visible area

When implementing scrollIntoView() with navigation buttons (up and down), I aim to display two items at a time to signal to the user that there are more items to navigate. However, the first and last items should retain their default behavior so the user u ...

PHP Pagination with AJAX and MySQL

I'm currently working on a website that functions as a forum, where posts are displayed dynamically using ajax. Upon user login, they encounter a 'orderby' dropdown selection, allowing them to choose the order of the posts. Select Menu < ...

Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null. The HTML layout includes: <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <select class="form-control" class="form-control" id="choose_country"& ...

Guidelines for accessing the value of the parent function upon clicking the button within the child function?

I have a pair of buttons labeled as ok and cancel. <div class="buttons-div"> <button class='cancel'>Cancel</button> <button class='ok'>Ok</button> </div> The functions I am working wi ...

Sort data with encryption based on chosen columns (table sort functionality)

I'm currently facing a challenge when it comes to sorting a table by column name. The data in the table is encrypted, so a simple sort by the column's direction (ascending or descending) isn't possible. I've been exploring options like ...

Adding JSON data to an array with a click - a step-by-step guide

As I dive into working with React and integrating API JSON data into my project, I've encountered a small hurdle. I've implemented a function that allows users to enter a search query, resulting in a list of devices associated with their input be ...

Label Overlapping Issue in React Select

Utilizing react-select version ^5.1.0, I am encountering an issue where the word "select" overlaps with the options when scrolling. An image has been attached for better clarification. How can I eliminate the occurrence of the select word overlapping my op ...

What could possibly be the issue with my PHP variables?

My PHP script uses a python script to retrieve new data. While I am successfully able to loop through and extract key2 and value2 from an array using foreach, I am facing issues with extracting the variables $address and $product to include in a $shell com ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

`How can I stop typescript from converting dynamic imports to require()?`

Currently, I am in the process of creating a Discord bot using discord.js. Interestingly, discord.js does not seem to be compatible with ESM modules, which has been causing some complications in my project. As a result, I have resorted to utilizing CommonJ ...

Steps for adjusting the matMenuTriggerFor area so it only triggers when hovering over the arrow

Hello there! I'm currently working on adjusting the trigger area for opening the next menu panel. Right now, the next menu panel opens whenever I hover over either the title or the arrow. However, my goal is to have the menu open only when I hover ove ...

Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functi ...

Select a date from the JQuery calendar, verify it against the database, and display any events scheduled for that date

I am working with a jQuery calendar that stores the selected date in a variable named "X". My goal is to retrieve events stored on that specific date from the Database and display them. Can anyone provide some guidance? <div id="calendar"></div&g ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method f ...

Highstock Highcharts showcase intricate date and time data displayed on the X-axis

Attempting to utilize a JavaScript timestamp as indicated in the documentation to apply it to the X-axis has proven to be a challenging task. Despite my efforts, I have been unable to successfully implement the date data for use with a datepicker. I have ...

Importing JSON Data into an HTML File

I need to load a JSON file containing HTML content into my main HTML file upon clicking a button. ABC.json includes: <li><img src="images/picture6.jpg" /></li> <li><img src="images/picture5.jpg" /></li> <li><i ...