Removing redundant names from an array using Typescript

My task involves retrieving a list of names from an API, but there are many duplicates that need to be filtered out. However, when I attempt to execute the removeDuplicateNames function, it simply returns an empty array.

const axios = require('axios');

interface Names {
  objectId: string;
  Name: string;
  Gender: string;
  createdAt: string;
  updatedAt: string;
}

function getNames() {
  const options = {
    method: 'GET',
    url: 'API.COM',
    headers: {
      'X-Parse-Application-Id': 'xxx',
      'X-Parse-REST-API-Key': 'xxx',
    },
  };

  return axios
    .request(options)
    .then(({ data }: { data: Names[] }) => {
      return data; // Return the retrieved data
    })
    .catch((error: any) => {
      console.error(error);
      throw error; // Rethrow the error to propagate it to the caller
    });
}

function removeDuplicateNames(names) {
    return [...new Set(names)];
  }
  

  async function main() {
    const namesFromApi = await getNames();
    const uniqueNames = removeDuplicateNames(namesFromApi);
  
    console.log('Original names:', namesFromApi);
    console.log('Names with duplicates removed:', uniqueNames);
  }
  
  main();

The structure of the API data is as follows

{
      objectId: '7igkvRJxTV',
      Name: 'Aaron',
      Gender: 'male',
      createdAt: '2020-01-23T23:31:10.152Z',
      updatedAt: '2020-01-23T23:31:10.152Z'
    }

Answer №1

When dealing with duplicate names and differing object fields, using a set may not be helpful.

Instead, a simple solution is to utilize the uniqBy function provided by the lodash library.

This function allows you to create a new array with duplicate items based on the 'Name' property removed, ensuring the order remains intact with only the first occurrence left.

By leveraging this library, common operations on collections, objects, and more can be streamlined.

For more information, refer to the documentation here.

import { uniqBy } from  'lodash';

// your code

function removeDuplicateNames(names) {
    return uniqBy(data, 'Name');
  }

Example of Output:

Data:

const data = [{
  objectId: '1',
  Name: 'Aaron',
  Gender: 'male',
  createdAt: '2020-01-23T23:31:10.152Z',
  updatedAt: '2020-01-23T23:31:10.152Z'
  },
  {
    objectId: '2',
    Name: 'Aaron',
    Gender: 'male',
    createdAt: '2020-01-23T23:31:10.152Z',
    updatedAt: '2020-01-23T23:31:10.152Z'
  },
  {
    objectId: '3',
    Name: 'Aaron',
    Gender: 'male',
    createdAt: '2020-01-23T23:31:10.152Z',
    updatedAt: '2020-01-23T23:31:10.152Z'
  },
  {
    objectId: '3',
    Name: 'Aaron1',
    Gender: 'male',
    createdAt: '2020-01-23T23:31:10.152Z',
    updatedAt: '2020-01-23T23:31:10.152Z'
  },
];

uniqBy(data, 'Name') result:

    [
      {
        objectId: '1',
        Name: 'Aaron',
        Gender: 'male',
        createdAt: '2020-01-23T23:31:10.152Z',
        updatedAt: '2020-01-23T23:31:10.152Z'
      },
      {
        objectId: '3',
        Name: 'Aaron1',
        Gender: 'male',
        createdAt: '2020-01-23T23:31:10.152Z',
        updatedAt: '2020-01-23T23:31:10.152Z'
      }
    ]

Answer №2

If you are looking to eliminate duplicates based on the Name key using the Set method on objects, follow these steps:

function filterDuplicatesByKeyName(items) {
    const keyValues = items.map((item) => item.Name);

    return items.filter((item, index) => !keyValues.includes(item.Name, index+1));
}

This implementation ensures that an element is removed from the array only if it has another occurrence (identified by the Name key) in the array after its own index.

Answer №3

In the Set class, checking for value equality is done using the SameValueZero algorithm. If you want to remove duplicate JavaScript object items, you can use the following approach:

interface User {
  objectid: string;
  name: string;
};  
function removeDuplicateNames(users: User[]): User[] {
  const record: { [string]: boolean } = {};
  const result: User[] = [];
  for (const item of users) {
    if (!record[item.name]) {
      result.push(item);
      recrod[item.name] = true;
    }
  }
  return result;
}

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

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

Unsuccessful Invocation of Servlet by Ajax Function

I have a situation where I am trying to trigger an Ajax javascript function from my jsp file, with the intention of loading a servlet for further processing. The issue I am facing is that even though I am able to pass values from the jsp to the ajax functi ...

Discovering details regarding cookies established by an external domain

Is it possible to retrieve the host address of the domain that created a cookie on my webpage? Here is the scenario I am facing: I am on "domain A" and have a script linked from "domain B". A method on "domain B" sets a cookie on my "domain A". How can ...

Resetting initial values with Velocity.js post-animation

After animating elements into view on a page, I want to defer further animation through CSS classes. However, Velocity keeps all animated properties in the style= tag, hindering CSS transitions. My solution involves resetting the CSS upon completion, but ...

Encountering a challenge when attempting to upgrade to Angular 9: Issue with transitioning undecorated classes with DI migration

As I transition from Angular 8 to Angular 9, I encounter an error during the step related to transitioning undecorated classes with DI. While attempting to migrate, I faced an issue with undecorated classes that utilize dependency injection. Some project ...

Combining individual TypeScript files together

Recently, I encountered an issue with 2 typescript files: a.ts: let some : string = "some"; b.ts: console.log(some); Surprisingly, when compiling both files together by including them in the tsconfig or command line, there was no error about 'som ...

AngularJs and graph representation

After attempting to generate charts using angular-chart, I followed all the necessary steps and requirements outlined in the documentation. However, upon completion, my canvas element failed to display any content. My HTML Layout: Here is a snippet of my ...

Guide to taking a screenshot of an HTML page using Javascript, Jquery, and HTML5 functionality

I am looking to add a unique feature to my website - the ability to capture the current image of my webpage with just the click of a button. Inspired by Google's "send feedback" function, I want to implement something similar on my own site. After res ...

"Trouble with React JS redirection feature failing to redirect as intended

Could someone please help me troubleshoot why the redirect function is not working in my code? There are no error messages showing up, but it seems like the Redirect call from the react-router-dom library is causing a problem. The console log displays &apo ...

Customizing Angular Forms: Set formcontrol value to a different value when selecting from autocomplete suggestions

How can I mask input for formControl name in HTML? When the autocomplete feature is displayed, only the airport's name is visible. After users select an airport, I want to show the airport's name in the input value but set the entire airport obje ...

Which option offers superior performance: using attributes through HTML or jQuery?

At times, I find myself needing to include special classes, divs, and attributes in my HTML code for jQuery scripts to function properly (the site's "no-JavaScript" version doesn't require these elements). You probably understand what I mean. I& ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Please provide a text file containing rows of numbers as input

Hey there, I'm encountering an issue with a text file that contains numbers in multiple rows. The error message I'm getting is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 I've checked ...

Creating Graphs for Dynamic JSON Data in Python

The JSON Graph Data I am working with does not have set keys and returns data for the last 180 days. The information consists of millisecond timestamps as keys and in-game prices as values. To effectively parse this data, I need to figure out a method to c ...

Is it possible to integrate Processing JS on top of an HTML element?

I have currently integrated Processing JS with the HTML canvas element on a website. The goal is to have the Processing JS animation run smoothly over the existing HTML elements on the page. You can check out the site at [usandthings.com][1] to get an idea ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...

Troubleshooting: Bootstrap Modal in .NET MVC not appearing on screen

Below is the code that manages order quotes and includes an if statement. The objective is to display an error message using TempData and Bootstrap Modal if the product quantity in the order exceeds the stock quantity. However, despite TempData not being n ...

Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one? For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are anot ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...