Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure:

results = [
  {name: 'Ana', country: 'US', language: 'EN'},
  {name: 'Paul', country: 'UK', language: 'EN'},
  {name: 'Luis', country: 'PH', language: 'SP'},
  {name: 'Tom', country: 'US', language: 'EN'}
];

I want to transform this array into a new one that looks like this:

countries = [
  {filter: 'country', value: 'PH'},
  {filter: 'country', value: 'UK'},
  {filter: 'country', value: 'US'},
];

To achieve this, I attempted the following code snippet:

countries = Array.from([...new Set(this.results.map(item => ({categoryOfFilter: 'country', value: item.country})))]);

However, despite using the set, the resulting array contains duplicates. It ends up looking like this:

countries = [
  {filter: 'country', value: 'US'},
  {filter: 'country', value: 'UK'},
  {filter: 'country', value: 'PH'},
  {filter: 'country', value: 'US'},
];

Do you have any insights or suggestions for solving this issue? Javascript has never been my strong suit so any help is greatly appreciated.

Answer №1

The Set object is a useful tool for storing unique values of any type, be it primitive values or references to objects.

When it comes to objects, Sets function differently. Each item in the Set is considered unique based on their object references, even if their attribute values are identical.

Here's how you can use Sets with objects:

results = [
  {name: 'Ana', country: 'US', language: 'EN'},
  {name: 'Paul', country: 'UK', language: 'EN'},
  {name: 'Luis', country: 'PH', language: 'SP'},
  {name: 'Tom', country: 'US', language: 'EN'}
];

// Create a set containing all unique country codes from the results array
const countryCodes = new Set(results.map(item => item.country));

// Transform the set values into an array and map it to target objects
const countries = [...countryCodes].map(value => {return {filter: 'country', value}});

console.log(countries);

Answer №2

Check out this awesome code snippet on CodePen: https://codepen.io/kyletanders/pen/NWqpWVX?editors=0012

Here's an example similar to the one shown:


    const data = [
      {name: 'Ana', country: 'US', language: 'EN'},
      {name: 'Paul', country: 'UK', language: 'EN'},
      {name: 'Luis', country: 'PH', language: 'SP'},
      {name: 'Tom', country: 'US', language: 'EN'}
    ];

    let unique = [...new Set(data.map(item => item.country))].map(x => {return {filter: 'Country', value: x}});
    console.log(unique);

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

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Only pass props to `Image` if they have a defined value

As I construct a blog platform using MDX and NextJS, I am creating a custom image component that utilizes the Next <Image> component. However, I've encountered a minor issue for which I have been unable to find a solution. The main question is: ...

Customizing colors for the progress bar in Angular Material

In my Angular 5 project, I am using a material progress bar and hoping to customize the colors based on the percentage progress. Despite trying various methods from other sources (including previous SO questions), I have been unsuccessful in getting it to ...

Using Angular, Typescript, and ngxs to manage state observables, one may wonder what exactly a variable ending with an exclamation mark (!) signifies. An example of this can be seen in the following code snippet:

Within my TS file, a declaration is present: import { Select } from '@ngxs/store'; @Injectable() export class someService { @Select(someSELECTOR) varName$!: Observable<someType[]>; elements$ = this.varName$.pipe( map(elements => e ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

Why is my Angular proxy failing to rewrite the path when making an HTTP GET request?

I am facing an issue with my proxy configuration where it is not redirecting as expected based on the rewrite configuration. You can find my proxy.config.json below: { "/sap": { "target" : "http://server.domain.com:8002", "secure" : fa ...

How can you develop a component that is reusable and make sure that the template reference variable can be assigned to the cdkDropList directive?

https://codesandbox.io/s/hn-kanban-34mvt?file=/src/app/dragDrop/dragDrop.component.html:0-1308 Is it possible to develop a reusable component that allows assigning the #newsList template reference variable to the cdkDropList directive, enabling other comp ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem. When handling request and response payloads in my API, everything seems to be working fin ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

The npm start command is no longer functioning in Angular 5

When attempting to start angular 5 with npm, I encountered an error that reads: TypeError: callbacks[i] is not a function Can anyone shed some light on where this error might be coming from? It seemed to pop up out of the blue and I can't seem to ...

Transform a string into a class in Typescript/Angular

In my application, I've created a reusable modal popup component that takes a string as input and dynamically loads other components based on that input. This approach allows me to use the same modal popup component for multiple modals in the app inst ...

Leveraging ES Module packages in Azure TypeScript Function Development

I'm encountering an issue while trying to utilize the p-map package in my Azure Function. The error message that I'm getting is as follows: A Worker failed to load function: 'serverless' with function id: '<id>'. Result: ...

Arranging secondary rankings through elimination within a multi-dimensional array

I am currently in the process of developing a golf ranking leaderboard using the JSON data provided below. While I can successfully rank the scores from lowest to highest, dealing with ties has proven to be quite challenging. Here's some context: The ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Recursive types in TypeScript allow for the definition of types that

Is there a way to implement the function below without utilizing any? Playground type MyType = { name: string, age: number, score: { prime: number, }, prize: { first: { discount: number } } } export const trim = ( myObj: ...

Use $lookup with nested subdocuments

I have four different collections that I need to connect and extract information from: "Groups", "Users", "LinkedTags", and "Photos". First, I start by retrieving all the groups from the "Groups" collection: group { id: 1, start: 10.12, linke ...

Despite the fact that one field is optional, failing to enter it will still result in the form being considered invalid

Although one of the fields is not mandatory, the form still shows as invalid when left empty. I have been attempting to resolve this issue without success. app.component.html <form [formGroup]="multiSelectForm"> <div formGrou ...

The issue with the demo variable not functioning properly within the ngOnChanges method of the child component

I am facing an issue in child.component.ts where I am using the demo variable with input(), but it is not showing up in the developer console. app.html <input type="text" placeholder="text" #val> <br> <button (click)="submitValue(val)"> ...

Collections of references pointing to collections of integer values

Is there a way to create an array of pointers that point to the first column of each row in a multidimensional integer array? Take a look at this code snippet as an example: #include <stdio.h> int day_of_year(int year, int month, int day); main() ...