identifying identical elements within an array

Once I received various user images, the resulting array looks like this:

[
    { label: "portrait", owner: "Jon" },
    { label: "house", owner: "Jim" },
    { label: "portrait", owner: "Jim" },
    { label: "portrait", owner: "Jane" },
    { label: "cat", owner: "Jane" }
]

In order to highlight entries with duplicate label values in the array (in this case: "portrait"), I am seeking assistance.

Ideally, I would like to flag items with a repeat occurrence of the label, distinguishing between those flagged as A for being repeated later in the array and those flagged as B for being the final occurrence (for example, both Jon's and Jim's portraits are flagged as A, while Jane's is flagged as B).

Any support provided on this matter would be greatly valued!

Answer №1

Not quite sure about your intentions, but perhaps aggregating the data could be the solution?

var data = [
    { name: "portrait", owner: "Jon" },
    { name: "house", owner: "Jim" },
    { name: "portrait", owner: "Jim" },
    { name: "portrait", owner: "Jane" },
    { name: "cat", owner: "Jane" }
];

var byName = {};

for (var i = 0, l = data.length; i < l; ++i) {
    if (!byName[data[i].name]){
        byName[data[i].name] = [];
    }
    byName[data[i].name].push(data[i].owner);
}

// byName == {portrait: ["Jon", "Jim", "Jane"], house: ["Jim"], cat: ["Jane"]}

var byOwner = {};

for (var i = 0, l = data.length; i < l; ++i) {
    if (!byOwner[data[i].owner]) {
        byOwner[data[i].owner] = [];
    }
    byOwner[data[i].owner].push(data[i].name);
}

Alternatively, you might prefer this approach:

var data = [
    { name: "portrait", owner: "Jon" },
    { name: "house", owner: "Jim" },
    { name: "portrait", owner: "Jim" },
    { name: "portrait", owner: "Jane" },
    { name: "cat", owner: "Jane" }
];

var byName = [];

for (var i = 0, l = data.length; i < l; ++i) {
    var done = false;
    for (var j = 0, k = data.length; j < k; ++j) {
        if (byName[j] && byName[j].name == data[i].name) {
            byName[j].data.push(data[i].owner);
            done = true;
        }
    }
    if (!done) {
        byName.push({name: data[i].name, data: [data[i].owner]});
    }
}

/*
byName == [
    {name: "portrait", data: ["Jon", "Jim", "Jane"]},
    {name: "house", data: ["Jim"]},
    {name: "cat", data: ["Jane"]}
] */

Let's throw in some random code for a bit of fun!

Answer №2

To optimize the picture array, my recommendation would be to iterate through each object in the array and assign a flag based on whether it is a duplicate or not. The concept is illustrated below with a working example. Each duplicated item will receive an 'A' flag, while the last duplicate will be marked with a 'B'. Objects that are unique will remain unflagged.

var picture_array = [
        {label: 'portrait', owner: "Jon"},
        {label: 'house', owner: "Jim"},
        {label: 'portrait', owner: "Jim"},
        {label: 'portrait', owner: "Jane"},
        {label: 'cat', owner: "Jane"}
    ],
    length = picture_array.length;

//Iterate through the picture_array

for(var i = 0; i < length; i++) {
    var picture = picture_array[i],
        label = picture.label;

    //Skip if the picture has already been flagged
    if (picture.flagged) {
       continue;
    }

    //Check for duplicates by comparing labels within the array
    var picture_a = picture;
    for(var j = i + 1; j < length; j++) {
        var picture_b = picture_array[j];

        //Flag matching duplicates accordingly
        if (picture_a.label == picture_b.label) {
            picture_a.flagged = 'A';
            picture_b.flagged = 'B';
            picture_a = picture_b;
        }
    }
}

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

How come AngularJS $onChanges isn't able to detect the modification in the array?

What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first? In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Can you replicate this website on your local device?

It seems straightforward to recreate a website by simply copying the files over, but it's not working for me. Despite copying all the scripts, images, and .html files, nothing is being displayed on the site. All the paths are correct, yet everything a ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Refreshing AJAX content with a dynamically adjusting time interval

I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, foll ...

Exploring the power of recursion within Angular directives and templates

While attempting to create a custom directive for displaying a tree structure, I encountered a strange issue. It appears that including the directive in its own template causes chaos in the angular compiler, leading to the browser process getting stuck in ...

What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse(). An example of the output provided by PM2: '{data: 0, informations: " ...

Refreshing the webpage section without requiring a full page reload

I am currently working on a Django website and I have been trying to update a specific section of the webpage without refreshing the entire page. However, most solutions I found online didn't work for me because the part I want to update is actually i ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

What is the best way for AngularJS ng-repeat to access the key of an item?

For more information, check out the documentation: https://code.angularjs.org/1.2.26/docs/api/ng/directive/ngRepeat The ngRepeat directive creates a template for each item in a collection. Each template has its own scope with the current item assigned t ...

What is the best way to display a dynamic JSON array in an HTML table?

I have a function that is triggered by a button press and updates an array order: var order = []; function updateCart(item) { var index = order.findIndex(i => i.id == item.id); if (index != -1) { order.splice(index, 1); order.p ...

Executing a callback within a promise: a step-by-step guide

One of my functions is designed to take a Section and return a Promixe. router.get('/menu_section', (req, res) => { Section.read(req.body) .then(d => { send(d, res); }) .catch(e => { e ...

Facing issue with React Native Flip Card functionality not working properly when trying to flip

I am currently working on developing a flip card game using GestureFlipView for the flip card animation. My goal is to display these flip cards in a 3X3 grid by utilizing components from React Native. However, I have encountered an issue where the cards ar ...

Using jQuery .sortable() to reorder list items and update their IDs based on their new positions

My apologies for my limited English skills, but here is what I am trying to achieve. I have a list structured like this: <ul id="sortable" class="sortable"> <li id="1">1</li> <li id="2">2</li> <li id="3">3</li> &l ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

Getting the ajax response in PHP while editing a popup is a common requirement in web development

When the edit button is clicked, I want a popup to appear with all selected values displayed using ajax. My response is sent in this format: $data = array('cdid' => $model->cdid, 'cid' => $model->cid, 'icdcode' = ...

Filter Vue.js dropdown by checking if a word is present in the array (partial match only)

https://jsfiddle.net/75f3c2po/ Is there a way to modify the Vue.js code above so that it filters by dropdown to match the entire array even if there are commas separating other words? Currently, it only matches if the type: BMW, but I would like it to als ...

What Could be the Reason Behind the Sharp Decline in My Google PageSpeed Insights Score?

Optimization On my desktop, I have successfully achieved a high page speed score of 96 on this site: https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fwww.usstoragecenters.com%2Fstorage-units%2Fca%2Falhambra%2F2500-w-hellman-ave&am ...

Multiple invocations of ngrx effects occur following its return of the value

When the value is returned, ngrx effects are triggered multiple times. loadMovies$: Observable<Action> = createEffect(() => { return this.actions$.pipe( ofType(counterActions.CounterActionTypes.IncrementCounter), flatMap(() => { ...

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...