Finding items with distinct sets of characteristics

My array consists of objects with various properties, for example:

[{"Account Name":"John Hill","Account Type":"Services","Organization":"A","Account Address":"2 Westall Rd"},
{"Account Name":"John Hill","Account Type":"Training","Organization":"A","Account Address":"2 Westall Rd"},
{"Account Name":"Dave Butcher","Account Type":"Engieering","Organization":"A","Account Address":"Level 1/55 Sunshine Blvd"},
{"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd},
{"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd"}]

Among the objects, there are duplicates in account names, which are unique due to the account type. I am looking for a way to filter the objects based on a combination of key values, such as Account Name && Account Type.

Some suggested solutions involve creating a new array with only the keys to filter, but I prefer to maintain all original keys in the object without reducing them.

The desired output should be like this:

[{"Account Name":"John Hill","Account Type":"Services","Organization":"A","Account Address":"2 Westall Rd"},
{"Account Name":"John Hill","Account Type":"Training","Organization":"A","Account Address":"2 Westall Rd"},
{"Account Name":"Dave Butcher","Account Type":"Engieering","Organization":"A","Account Address":"Level 1/55 Sunshine Blvd"},
{"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd}]

Answer №1

const data = [{"Name":"Alice Smith","Type":"Sales","Company":"X","Address":"123 Main St"},
{"Name":"Alice Smith","Type":"Marketing","Company":"X","Address":"123 Main St"},
{"Name":"Bob Johnson","Type":"Engineering","Company":"Y","Address":"456 Elm St"},
{"Name":"Cathy Brown","Type":"Management","Company":"Z","Address":"789 Oak St"},
{"Name":"Cathy Brown","Type":"Management","Company":"Z","Address":"789 Oak St"}]

const filteredData = data.reduce((acc, current) => {
  const duplicate = acc.find(item => (item['Name'] === current['Name']) && (item['Type'] === current['Type']));
  if (!duplicate) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);

console.log(filteredData);

Answer №2

Utilize the uniqueness of keys in JavaScript objects

function removeDuplicatesFromArray(arr){
    let uniqueObjects ={}
    arr.forEach(item => {
        // check all object
        //uniqueObjects[JSON.stringify(item)]=item;
        // check only Account Name and Account Type 
        uniqueObjects[item['Account Name']+item['Account Type']]=item;
    });
    return Object.values(uniqueObjects);
}

Answer №3

Utilize a Map data structure. Iterate through the array and for each item, generate a unique key using the combination of the Account Name and Account Type. Then, assign the entire object as the value for that key using the set method. Finally, utilize values() to obtain a deduplicated array.

const data=[{"Account Name":"John Hill","Account Type":"Services",Organization:"A","Account Address":"2 Westall Rd"},{"Account Name":"John Hill","Account Type":"Training",Organization:"A","Account Address":"2 Westall Rd"},{"Account Name":"Dave Butcher","Account Type":"Engieering",Organization:"A","Account Address":"Level 1/55 Sunshine Blvd"},{"Account Name":"Jake Wellington","Account Type":"Management",Organization:"A","Account Address":"11 Maroochy Rd"},{"Account Name":"Jake Wellington","Account Type":"Management",Organization:"A","Account Address":"11 Maroochy Rd"}];

const map = new Map();

for (const obj of data) {
  const key = `${obj['Account Name']}-${obj['Account Type']}`;
  map.set(key, obj);
}

console.log([...map.values()]);

Answer №4

One effective method is the hash group technique for filtering based on multiple properties:

const data = [{"Account Name":"John Hill","Account Type":"Services","Organization":"A","Account Address":"2 Westall Rd"},{"Account Name":"John Hill","Account Type":"Training","Organization":"A","Account Address":"2 Westall Rd"},{"Account Name":"Dave Butcher","Account Type":"Engieering","Organization":"A","Account Address":"Level 1/55 Sunshine Blvd"},{"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd"},{"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd"}];

const uniqHashes = data.reduce((acc, item) => {
    const hash = [item['Account Name'], item['Account Type']].join('-');
    acc[hash] ??= item
    return acc;
}, {});

const uniqs = Object.values(uniqHashes);

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

Answer №5

This method aims for simplicity. It gathers all unique rows into a new array and verifies if an equivalent row already exists before adding it. The time complexity is O(n^2), which may not be the most efficient for very large datasets. In such cases, a more efficient solution like the one suggested by @Andy (using composite keys and a map for O(n) complexity) would be preferable.

const records = [{"Account Name":"John Hill","Account Type":"Services","Organization":"A","Account Address":"2 Westall Rd"},
  {"Account Name":"John Hill","Account Type":"Training","Organization":"A","Account Address":"2 Westall Rd"},
  {"Account Name":"Dave Butcher","Account Type":"Engieering","Organization":"A","Account Address":"Level 1/55 Sunshine Blvd"},
  {"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd"},
  {"Account Name":"Jake Wellington","Account Type":"Management","Organization":"A","Account Address":"11 Maroochy Rd"}]

const uniqueRows = []
records.forEach((row) => {
  if (uniqueRows.find((existingRow) => (row['Account Name'] === existingRow['Account Name'] ) && (row['Account Type'] === existingRow['Account Type'])) === undefined) {
    uniqueRows.push(row);
  }
})

console.log(uniqueRows);

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

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

Including jQuery in an Angular project generated with JHipster

I am facing a challenge with integrating jQuery into my Jhipster Angular project as a newcomer to Jhipster and Angular. My goal is to customize the theme and appearance of the default Jhipster application, so I obtained a theme that uses a combination of ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

Is it possible to pass function attributes through a single function in Javascript?

I'm currently trying to determine the most effective method to indicate that the game has ended. I have my gameover() function function gameover(chk, scoreOne, scoreTwo) { if (chk === true) { // Game over // Displ ...

Is it possible to utilize JavaScript for displaying a continuous stream of images?

In this scenario, you are tasked with working with an image API and need to send a POST request to retrieve an image stream for display on the rest of your webpage. While I am able to use jQuery to make an ajax request to the service upon page load, I am ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Creating an image slideshow with a looping JavaScript array: Step-by-step guide

One issue with the program is that when it runs, only the last array value image is displaying on the screen while the other images are not. Below is the HTML code: <img id="mg" alt="image not found"> And here is the JavaScript code: var images=[ ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

https://i.sstatic.net/0jyFI.png There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.u ...

Establishing parameters in a Socket.io chatroom

I am encountering an issue when attempting to store information in the socket room variables. The error message I receive is: UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'host' of undefined This is the snippet of my code: io ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

What could be causing the 304 error when using $http.get?

I'm a newcomer to angular and facing an issue with a service that was functioning perfectly, but suddenly stopped. The service I am referring to has the following method. this.retrieveForms = function() { return $http.fetch("/forms"). then(fu ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

Using JavaScript, insert unique texts into div elements with the same id

I am working with 5 divs that have the id of "correctAnswer". In my array, I have 5 elements. How can I insert these 5 elements into the 5 divs? Here is the approach I am taking. var answers =["David Bowie","AM","Australia","Boneface","Sound City"]; for ...

What could be the reason for the absence of definition for 'res'?

As I work on coding a bot using discord.js, I am facing an issue while trying to set up a system where the bot can send a message as long as it is not blacklisted. However, every time I attempt to run the function, I encounter this error message: Reference ...

Enhancing ajax requests with headers in Ember.js

My goal is to configure request headers for my emberjs application. However, when setting it up in the initializer, the client_id appears as [object Object] instead of the actual value. This is the initializer that runs when the application starts. Apikey ...

JavaScript Proxies: no activation of 'set' when making changes to objects within an array

I am working with an array that is filled with objects let objectArray = [{ id: 1, name: "John" }, { id: 2, name: "Bill" }, { id: 3, name: "Mike" }]; Next, I create a proxy with a set handler using my array as the target let proxy = new Prox ...

Retrieve an element within a jQuery each loop

I'm currently implementing AJAX functionality to retrieve cart items from the server and display them within a cart when a customer clicks on the "My Cart" button. Here is the model for the cart: public class Cart { [Key] public i ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Utilizing Three.js Collada for loading and displaying several Collada objects within Three.js framework

I am struggling to load multiple objects with collada and the solutions provided on stack overflow are not working for me. While I was successful in loading with three.js export, collada is giving me trouble. I have shared my code below. Any help would be ...