Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below:

let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 13 },
        { name: "Siva", SalseVersion: 10, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 },...]

Then I expect the following result:

[{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
 { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }]

If the array contains the data shown below:

let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 14},
        { name: "Siva", SalseVersion: 12, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 },...]

Then I expect the following result:

        [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }
        { name: "Suresh", SalseVersion: 12, MarketingCode: 14},
        { name: "Siva", SalseVersion: 12, MarketingCode: 14 }]

I have attempted to solve this by utilizing the following method:

let arr = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 13 },
        { name: "Siva", SalseVersion: 10, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }]


var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1].SalesVersion == sorted_arr[i].SalesVersion && sorted_arr[i + 1].MarketingCode == sorted_arr[i].MarketingCode) {
        results.push(sorted_arr[i]);
    }
}

console.log(results);

Unfortunately, I was unable to retrieve the duplicated values. Can you assist me in resolving this issue?

Note: Please note that this solution should work regardless of whether the SalseVersion and MarketingCode values are strings, numbers, or Booleans.

I have tried some of the solutions provided, but I encountered the following error:

https://i.sstatic.net/ylOzt.jpg

Answer №1

Utilize the reduce method for this task.

Initially, the first reduce function will group the values by combining the values of SalseVersion and MarketingCode.

Subsequently, the second reduce function will verify if the group contains more than one element. If so, it will concatenate the values into a single array.

let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },{ name: "Suresh", SalseVersion: 12, MarketingCode: 14},{ name: "Siva", SalseVersion: 12, MarketingCode: 14 },{ name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }];

let result = Object.values(array.reduce((c, v) => {
  let k = v.SalseVersion + '-' + v.MarketingCode;
  c[k] = c[k] || [];
  c[k].push(v);
  return c;
}, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []);

console.log( result );

Answer №2

If you're looking for elements in an array that have at least one other element with similar properties, you can achieve this by using the .filter method and then sorting the results:

const findDuplicates = array => {
  const filteredDuplicates = array.filter(({ name, SalseVersion, MarketingCode }, i, arr) => (
    arr.find((item, findI) => (
      findI !== i &&
      SalseVersion === item.SalseVersion &&
      MarketingCode === item.MarketingCode
    ))
  ));
  return filteredDuplicates.sort((a, b) =>
    String(a.SalseVersion).localeCompare(String(b.SalseVersion), 'kn') ||
    String(a.MarketingCode).localeCompare(String(b.MarketingCode), 'kn')
  );
};

console.log(findDuplicates([{name:"Ramesh",SalseVersion:10,MarketingCode:11},{name:"Suresh",SalseVersion:12,MarketingCode:13},{name:"Siva",SalseVersion:10,MarketingCode:14},{name:"Sakthi",SalseVersion:10,MarketingCode:11}]))
console.log(findDuplicates([{name:"Ramesh",SalseVersion:10,MarketingCode:11},{name:"Suresh",SalseVersion:12,MarketingCode:14},{name:"Siva",SalseVersion:12,MarketingCode:14},{name:"Sakthi",SalseVersion:10,MarketingCode:11}]))

Answer №3

Make sure to update your code with the following changes:

let list = [{ name: "John", Version: 10, Code: 11 },
    { name: "Jane", Version: 12, Code: 14},
    { name: "Jill", Version: 12, Code: 14 },
    { name: "Jack", Version: 10, Code: 11 },
    { name: "Jenny", Version: 10, Code: 11 }]

// Implement a custom sorting function
var sorted_list = list.slice().sort((a,b) => {
     if(a.Version === b.Version) {
          return a.Code - b.Code;
      }
      return a.Version - b.Version;
});
var results = [];
for (var i = 0; i < sorted_list.length - 1; i++) {
    if (sorted_list[i + 1].Version == sorted_list[i].Version && sorted_list[i + 1].Code == sorted_list[i].Code) {
        /* push both elements when there is a match, unless it has already been pushed for 2 matches */
       if (i >= 1 && sorted_list[i - 1].Version == sorted_list[i].Version && sorted_list[i - 1].Code == sorted_list[i].Code) {
         results.push(sorted_list[i+1]);
       } else {
         results.push(sorted_list[i], sorted_list[i+1]);
       }            
    }
}

console.log(results);

Answer №4

In a nutshell, you can achieve grouping by sorting the array based on the desired key. This will result in an array where all keys and their corresponding values are grouped together.

Subsequently, you can filter the array by comparing each key with its adjacent values to identify the desired groups.

var array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }],
    keys = ['SalseVersion', 'MarketingCode'],
    result = array
        .sort((a, b) => {
            var diff;
            keys.some(k => diff = a[k] - b[k]);
            return diff;
        })
        .filter((o, i, a) => 
            keys.every(k => a[i - 1] && a[i - 1][k] === o[k]) ||
            keys.every(k => a[i + 1] && o[k] === a[i + 1][k])
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If the data is unsorted, an alternative method involves using a hash table to temporarily store and identify the first object in each group or detect duplicates within the group.

var array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }],
    keys = ['SalseVersion', 'MarketingCode'],
    result = array.reduce((hash => (res, obj) => {
        var key = keys.map(k => obj[k]).join('|');
        if (key in hash) {
            if (hash[key]) {
                res.push(hash[key]);
                hash[key] = false;
            }
            res.push(obj);
        } else {
             hash[key] = obj;
        }
        return res;
    })(Object.create(null)), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

The database threw an error: "Duplicate key found in collection causing MongoError: E11000"

I'm currently in the process of updating an object within an array found in a document "state": [], "users": [{ "ready": false, "_id": { "$oid": "5fb810c63af8b3 ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

TS6059 found in excluded folder

I'm facing an issue with my tsconfig.json file that looks like this: {"compilerOptions": { "module": "commonjs", ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

Loop Through Mongoose to Retrieve Multiple Objects

I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order. The user collection consists of an array called 'order history', which ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

Can PHP retrieve data when the form submit function is overridden with AJAX?

I have customized the .submit function of a form on this webpage. It is being loaded inside the #mainContent in an "index.php" and I want the Submit button to only replace this #mainContent. My goal is to retrieve data from this form and send it to a .php ...

What is the best way to replace the empty months in an array with zeros?

I have a dataset with information about customer data for specific months, but some months are missing. The current array looks like this: dashCustomerData = [{ "req_count": 1, "revenue": 11868.19, "getMonth": "August", "count(compID)": 2 ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

Can you help me figure out what's not quite right with my form validation function

I'm struggling with a form that is supposed to validate user input for Name, Email, Phone Number, Age, and Income. The validateForm function should check for errors and display red textboxes and error messages if any errors are found. However, the fun ...

What steps should I take to resolve this issue? ERROR TypeError: Unable to access property 'user' of null object

Is there a way to resolve the error I'm encountering in my project? The error message is: ERROR TypeError: null is not an object (evaluating 'userdata.user'). Using React Native Expo, I am facing this issue after logging into my app and navi ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

How to Dynamically Enable or Disable a Button in Angular 2 Based on Text Field Values

I am facing a situation where my UI contains multiple text boxes and dropdown fields. My goal is to activate a button on the UI as soon as one of these fields has a value. I have set up a function that is triggered by the ngModel values assigned to these f ...

What are some ways to prevent having to constantly check for the existence of an object within another object when working

<template> <img :src="user.avatar_thumbnail"> <a :href="user.profile.link"/> </template> <script> export default { data: function () { user: {} }, ...

Conceal the div by clicking outside of it

Is there a way to conceal the hidden div with the "hidden" class? I'd like for it to slide out when the user clicks outside of the hidden div. HTML <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.c ...

Employ the faker.js library to automatically create a form within casperjs environment

When using Casperjs to fill and submit forms, it is necessary to manually input the data each time. On the other hand, Faker.js can generate fake data that can be used in forms. The question then arises - how can these two be combined effectively? Consider ...