Question:
How to delete duplicate names from Array in Typescript?

Problem:

I am fetching data from an api containing a long list of names. Many of them are duplicates and I want to filter the names so there aren't any duplicates. When trying to run the removeDuplicateNames function it just 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 api data looks like this

{

      objectId: '7igkvRJxTV',

      Name: 'Aaron',

      Gender: 'male',

      createdAt: '2020-01-23T23:31:10.152Z',

      updatedAt: '2020-01-23T23:31:10.152Z'

    }


Solution:

You try to use the Set over objects. If you want to filter duplicates by Name key you should:


function removeDuplicateNames(names) {

    const namesOnly = names.map((name) => name.Name);


    return names.filter((name, index) => !namesOnly.includes(name.Name, index+1));

}


This way, you remove an element from the array only if it has another occurrence (by Name key as an ID) in the array (after its own index).


Answered by: >Cc Xu

Credit:> StackOverflow


Blogs Link: 

>How to solve encoding issue when writing to a text file, with Python?

>Python Error Solved: pg_config executable not found

>How to solve XGBoost model training fails in Python

>Python Error Solved: load_associated_files do not load a txt file

>How to build interactive_graphviz in Python


Ritu Singh

Ritu Singh

Submit
0 Answers