Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values.

Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the list should be updated only if new data is available.

response= [{"id":"0DRDCH03DR51GGJGJNP80F7XZ8","value":"36af1784bec4_566601260"},{"id":"0DRDCFYGM2CAHAXYK96BPT9RHV","value":"36af1784bec4_566601140"},...]

listData = [];
for(let data of response) {
    let tempValue = {id: '', time: ''};
    let value = data.value.split('_')
    if (value.length==2) {
        if(value[value.length-1].length==2) {
            tempValue.id = value[0];
            tempValue.time = value[1];
        }
        let isPresent = false;
        if(this.listData.length>0){
            for(let value of this.listData){
                if(value.time===tempValue.time){
                    isPresent = true;
                }
            }
        }
        if(!isPresent) {
            this.listData.push(tempValue);
        }
    }

    }

The resulting list:

listData = [{id:'36af1784bec4', time: '566601140'},...]

The above code provides me with a listData array containing unique values. Despite attempting methods like array.filter and new Set, I couldn't achieve the desired outcome.

If you have any suggestions on how to improve the efficiency of this process, please share them with me.

Answer №1

If you're looking to eliminate duplicates, check out this code snippet.

var obj = {};

for ( var i=0, len=response.length; i < len; i++ )
    obj[response[i]['id']] = response[i]; // consider id as unique identifier

response = new Array();
for ( var key in obj )
    response.push(obj[key]);

console.log(response); // list of non-duplicate data 

Edit:

To perform a thorough check on a specific property for duplicates, try this approach.

function removeDuplicates(myArr, prop) {
    return myArr.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
}


console.log(removeDuplicates(response,['id','value'])); // specify either 'id' or 'value' for the second parameter.

Answer №2

My solution seems promising

for(let item of response) {
    if(!this.listData.find((ldata) => item.value.substring(item.value.lastIndexOf('_')+1) === ldata.time)) {
        let tempVal = {id: '', time: ''};
        let val = item.value.split('_')
        if (val.length==2) {
            if(val[val.length-1].length==2) {
                tempVal.id = val[0];
                tempVal.time = val[1];
            }
            this.listData.push(tempVal);
        }
    }
}

Answer №3

To achieve an optimal solution (loop only once i.e. O(n)), use object property to check if the property has already been added. This way, you can avoid looping to find out if the property has already been added.

Here is a sample solution:

let response = [{
    "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
    "value": "36af1784bec4_566601260"
  }, {
    "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
    "value": "36af1784bec4_566601260"
  }, {
    "id": "0DRDCFYGM2CAHAXYK96BPT9RHV",
    "value": "36af1784bec4_566601140"
  }],
  listData = [],
  tempObj = {};
for (let data of response) {
    let value = data.value.split('_');
  if (!tempObj.hasOwnProperty(value[1])) {
    tempObj[data.value[1]] = "";
    listData.push({
      id: value[0],
      time: value[1]
    });
  }
}

console.log(listData);

Update: As per feedback, now checking only for duplicate time values

Answer №4

You can achieve the same result by converting objects to strings using JSON.stringify as shown below :

let response = [{
  "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
  "value": "36af1784bec4_566601260"
}, {
  "id": "0DRDCFYGM2CAHAXYK96BPT9RHV",
  "value": "36af1784bec4_566601140"
}, {
  "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
  "value": "36af1784bec4_566601260"
}];

let o = response.reduce((acc, cv) => {
  if (!acc[JSON.stringify(cv)]) {
    acc[JSON.stringify(cv)] = true; //something non-falsy
  }
  return acc;
}, {});

let res = Object.keys(o).map(x => JSON.parse(x));
console.log(res);

Edit As user3297291 mentioned

It is important to note that JSON.stringify({ a: 1, b: 2}) !== JSON.stringify({ b: 2, a: 1 })

Hence, the above approach may not work in such cases.

A more efficient solution would be

let response = [{
  "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
  "value": "36af1784bec4_566601260"
}, {
  "id": "0DRDCFYGM2CAHAXYK96BPT9RHV",
  "value": "36af1784bec4_566601140"
}, {
  "id": "0DRDCH03DR51GGJGJNP80F7XZ8",
  "value": "36af1784bec4_566601260"
}];

let o = response.reduce((acc, cv) => {
  if (!acc[cv.value]) {
    acc[cv.value] = true; //something non-falsy
  }
  return acc;
}, {});

let res = Object.keys(o).map(x => {
  let t = x.split('_');
  return {
    id: t[0],
    time: t[1]
  };
});
console.log(res);

Answer №5

To achieve this task, you can utilize a map function to gather the ids and then apply a filter function to eliminate duplicates:

const response = [{"id":"0DRDCH03DR51GGJGJNP80F7XZ8","value":"36af1784bec4_566601260"},{"id":"0DRDCFYGM2CAHAXYK96BPT9RHV","value":"36af1784bec4_566601140"}];

const ids = response.map(item => item.value.split('_')[0]).filter((item, index, array) => index === array.indexOf(item));

console.log(ids);

Alternatively, you can also use a reduce function:

const response= [{"id":"0DRDCH03DR51GGJGJNP80F7XZ8","value":"36af1784bec4_566601260"},{"id":"0DRDCFYGM2CAHAXYK96BPT9RHV","value":"36af1784bec4_566601140"}];

const ids = response.reduce((accumulator, currentItem) => {
  const id = currentItem.value.split('_')[0];
  return accumulator.includes(id) ? accumulator : [...accumulator, id];
}, []);

console.log(ids);

Answer №6

Recent versions of JavaScript now support relying on the consistency of object structure. This means we can use stringification and comparison of two strings to produce accurate results:

JSON.stringify({id:0, name:foo}) === JSON.stringify({id:0, name:foo}) // true

When dealing with an array of objects:

  1. Stringifying an object for testing
  2. Iterating through a collection of objects and stringifying each one
  3. Comparing the two strings created

This approach is beneficial as it eliminates the need to know specific key names, working effectively with any type of object...

arr = [{object}, {object2}, {etc...}]
test = JSON.stringify(obj);

for ( let i = 0, j = arr.length; i < j; i++ ) {
  let testAgainst = JSON.stringify(arr[i]);
  if (test === testAgainst) { 
    console.log('matches');
  } else {
    console.log('no match');
  }
}

By comparing two strings, you can easily identify matches. Feel free to leave a comment if there are any additional aspects to consider.

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

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Integrating a title field into every p-column with ng-template

I am exploring ng-templates for the first time. I have managed to customize each column to display names accurately, but I am encountering an issue. I would like to incorporate a title field in order to show a tooltip with the full name when hovering over ...

Special effects for the images动画效果。

Is there a way to add animation effects to images in the about section using this code: <div id="about" class="row section bgimg3"> <div class="col-sm-8"> <h2 style="color:black;">Want to Know More About me?</h2> ...

When the previous textbox is filled, the cursor will automatically move to the button

Utilizing an RFID reader where students tap their ID to display basic info, a hidden button on the form opens a modal with various purposes for selection. The challenge is shifting focus of cursor to the button and automatically clicking it when the last ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...

Adjusted position of the viewport if the DOM element containing the renderer is not located at the top of the display

I've come across an issue with a three.js scene within an Angular custom directive in the view. At the top, there's a navigation bar for switching between views (pretty standard so far). I set up a simple scene with a cube and basic camera rotati ...

I have a collection of emails stored as a string that I would like to convert into a json or javascript object and store in a mongodb

After selecting multiple user emails, I receive the following data: "participants" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294b5b404847695d41405b4d5b465c5d4c074a4644">[email protected]</a>,<a href="/ ...

Evaluating different attributes within a single entity

I was attempting to write some code that checks if two individuals share the same birthday. Person "a" and person "b" do not have the same birthday, yet the console output shows: a was born on day 1 a has the same birthday as a a has the same birthday as ...

Using AngularJS API within a standalone function: Tips and tricks

I'm diving into the world of AngularJS and I want to make an HTTP GET request to a distant server without messing up my current view code. After some research, I discovered a way to execute a function right after the HTML is loaded by using a standalo ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

Combining JSON and JavaScript for embedding a SPARQL query into an HTML document

I have successfully implemented an HTML + SPARQL + JSON + JavaScript program, which can be viewed here: Below is the code snippet for the SPARQL + JSON + JavaScript: function retrieveData() { var query = "PREFIX : <http://dbpedia.org/resource/> P ...

Tips for populating a DOJO Select using JSON data that includes various parameters instead of just label and value

I am trying to populate a DOJO select element with JSON data where the item values for value are expressed by the code property. Here's an example of what I have: //require dojo Select var select = new Select({ name: "stateSelect", ...

Exploring JSON information containing colons in the labels

I am having trouble accessing JSON data in Angular that contains a colon in the label (refer to responsedata). This is the code causing issues: <li ng-repeat="i in items.autnresponse.responsedata | searchFor:searchString"> <p>{{i.autn:numhits} ...

jQuery Autocomplete - struggling to pinpoint the exact location where the width of the suggestions div is being defined

I have successfully implemented jQuery Autocomplete, but I am facing an issue with adjusting the width. Currently, it is set to 268px in Firebug, however, I would like it to be 520px. After checking the stylesheet, I couldn't locate where the width o ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Can you explain the meaning of the code snippet provided?

<script type="text/javascript> window.onload = function(){ //execute some code here },function(){ // execute another piece of code here }(); </script> Is this code indicating that multiple function ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Python: How to determine if a specific part of an element is present in an array?

I have a list as shown below: ['MLPClassifier-81991331-57fe-40f8-86b2-fa570e8a9010', 'RandomForestClassifier-fbf96287-c16b-4e1e-ba10-66d5747742c7', 'KNeighborsClassifier-34f6b483-618f-407a-88bb-902972db40db'] If I define mod ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Problem with Onsen UI navigation: It is not possible to provide a "ons-page" element to "ons-navigator" when attempting to navigate back to the initial page

Hi, I am having trouble with navigation using Onsen UI. Here is the structure of my app: start.html: This is the first page that appears and it contains a navigator. Clicking on the start button will open page1.html page1.html: Performs an action that op ...