Identify the distinct item by its name within the array

I need assistance in filtering out unique place names from the list Array's places Array. Below is an example of the array data=>

"list":[
   {
      "id":1,
      "uID": 1 
      "places":[
         {
            "name":"USA"
         },
         {
            "name":"USA"
         },
         {
            "name":"GER"
         }
      ]
   },
   {
      "id":2,
      "uID":2
      "places":[
         {
            "name":"USA"
         },
         {
            "name":"GER"
         },
         {
            "name":"GER"
         }
      ]
   }
]

The desired output should look like this =>

"list":[
   {
      "id": 1,
      "uID": 1 
      "places":[
         {
            "name: USA"
         },
         {
            "name: GER"
         }
      ]
   },
   {
      "id: 2,
      "uID":2
      "places":[
         {
            "name: USA"
         },
         {
            "name: GER"
         }
      ]
   }
]

Your help with this is greatly appreciated.

Answer №1

To transform each element in the list to a new value, you can utilize the Array.map() method.

In order to eliminate duplicate locations, you can employ a Set object.

The Set is initialized with an array of location names obtained through another .map() operation. This will result in a collection of distinct location names within the Set.

Subsequently, these unique locations are set as the 'places' attribute for each resultant item.

const elements = [ { "id":1, "uID": 1, "places":[ { "name":"USA" }, { "name":"USA" }, { "name":"GER" } ] }, { "id":2, "uID":2, "places":[ { "name":"USA" }, { "name":"GER" }, { "name":"GER" } ] } ]

const output = elements.map(({ places, ...obj }) => {
    const uniqueLocations = new Set(places.map(item => item.name));
    return { ...obj, places: [ ...uniqueLocations].map(name => ({ name })) }
})

console.log('Output:', output);
.as-console-wrapper { max-height: 100% !important; }

Answer №2

To filter out duplicates, consider using the `Set()` function with the `add()` method. For more detailed information, check out this helpful resource:

Answer №3

  1. Transform the object(s) within the places array into a JSON string using JSON.stringify().
  2. Utilize new Set() to ensure uniqueness in the JSON strings.
  3. Convert the unique results from step 2 back into an array using Array.from().
  4. Parse each JSON string in the array obtained from step 3 back into its original object using JSON.parse().
list = list.map(x => {
    x.places = Array.from([...new Set(x.places.map(x => JSON.stringify(x)))])
        .map(x => JSON.parse(x));

    return x;
})

Check out this Sample Typescript Playground

Answer №4

const bar = {
"list":[
   {
      "id":1,
      "uID": 1,
      "places":[
         {
            "name":"USA"
         },
         {
            "name":"USA"
         },
         {
            "name":"GER"
         }
      ]
   },
   {
      "id":2,
      "uID":2,
      "places":[
         {
            "name":"USA"
         },
         {
            "name":"GER"
         },
         {
            "name":"GER"
         }
      ]
   }
]};

const updatedList = bar.list.map(item => {
  let filteredPlaces = [];
  item.places.forEach(loc => {
    const existingLocs = filteredPlaces.some(elem => elem.name === loc.name);
    if (!existingLocs) {
      filteredPlaces.push(loc);
    }
  });
  item.places = filteredPlaces;
  return item;
});

console.log(updatedList)

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

Unveiling typescript property guards for the unknown data type

Is there a way to type guard an unknown type in TypeScript? const foo = (obj: unknown) => { if (typeof obj === 'object' && obj) { if ('foo' in obj && typeof obj.foo === 'string') { r ...

Guide to Implementing StoreApi in Zustand LibraryLearn how to utilize Store

While reading the documentation for zustand, I came across a useful piece of information. In addition to the standard `set` and `get` parameters, there is an extra parameter called `api` in the StateCreator function. Check out the example below: import cr ...

What's the reason Perl isn't calculating the math in this situation?

My scenario involves an array filled with hash references: my @price = ( { id => '1', label => 5.00 }, { id => '2', label => 7.50 }, ); Alongside this, I have two varia ...

Struggling to meet PWA lighthouse test requirements even with service worker correctly installed

Recently, I've been diving into PWA development and I've encountered a roadblock. Despite successfully setting up my service worker and caching files, my app is not receiving the PWA mark for being installable when tested with Lighthouse. I' ...

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...

The system could not find the command "tsc" as an internal or external command, or as an operable program or script file

I'm new to using type script and I'm having trouble compiling my files. When I press Ctrl+Shift+B in VS Code, I receive the error message "tsc is not recognized." I installed typescript using npm. C:\Users\sramesh>npm install -g t ...

Is there a way to retrieve the requested data in useEffect when using next.js?

As a newcomer to next.js and TypeScript, I am facing an issue with passing props from data retrieved in useEffect. Despite my attempts, including adding 'return scheduleList' in the function, nothing seems to work. useEffect((): (() => void) = ...

Autoselecting Dropdown Field on Wordpress Contact Form 7 Depending on Referral URL

I have been referencing the following two answers: Wordpress Contact Form 7 dynamically select dropdown field based on url Auto-select fields in Contact form 7 based on referral link The code snippet below is currently inserted in the CSS block on the / ...

The specified reference token grant value of [object Object] could not be located in the store

Currently, I am working with NestJs along with the oidc passport strategy using identityserver. Below is a snippet of the code: import { UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; ...

Default Filter for Lookup Dialog in Dynamics CRM 2011

I am attempting to customize a lookup dialog to default to a specific entity type. While working on the Connection form, I am checking the entity type of record1id and attempting to use that information to set the defaulttype attribute on record2id. My c ...

We are hosting an event focused on DOM text selection outside of Input or TextArea elements

I need help finding a Javascript event that triggers when a user highlights paragraph text with their mouse on a web page. Once the text is highlighted, I want to access it using window.getSelection(). Just to clarify, I am not looking for ways to capture ...

Hold off on showing the image until it has finished loading

// Here's the code snippet angular .module('imgapp', []) .controller('mainCtrl', mainCtrl); function mainCtrl() { var vm = this; vm.first = { title: 'Image 1', url: 'http://www.image-mapper.com ...

Warning: Stack Smashing has been detected after using the `fgets`

When entering two strings, string1 and string2, the goal is to remove any instances of the letters in string2 from string1. The issue arises with a stack smashing detection error occurring after inputting the second string. The rmchr function seems to work ...

Is it possible to bypass the same-origin policy when creating AJAX client code for a Google AppEngine site?

I am collaborating with someone who has a Google AppEngine website with a custom API located there. My goal is to create AJAX Javascript code that interacts with the custom API on the site, but I am facing difficulties due to the same-origin policy. JSONP ...

Avoid changing the format when sending a JSON string to Node

I am attempting to send JSON data to a Node application using a POST request, which will then be retrieved through a GET request. On the client side, I create a JSON string representing the model and send it to the server: $.post(serverURL, ko.mapping.toJ ...

Utilizing Material UI (mui) 5.0 within an iframe: Tips and tricks

Attempting to display MUI components within an iframe using react portal has resulted in a loss of styling. Despite being rendered within the iframe, MUI components seem to lose their visual appeal when displayed this way. Most resources discussing this is ...

Long Waiting Time for the Ionic 2 Splash Screen

I've had struggles with the splash screen while developing several apps using ionic 2. The splash screen seems to take ages to disappear, and I understand that it's influenced by the number of plugins used and their response time. Is there a way ...

Using a different method to handle multiple callbacks in Angular or a suitable replacement for $.Callbacks

Is there a similar functionality in Angular to jQuery $.Callbacks? I am seeking a straightforward method to manage callback lists within Angular. My goal is to achieve the following using Angular: function Broadcast(){ var self= this; this._status ...

Tips for sending a structured search query to the findOne() function in MongoDB with Node.js

I have a Restful service built with node.js that takes user input to create a query string for MongoDB. However, whenever I try to pass this query to findone() in MongoDb and call the service, it displays a "query selector must be an object" message in the ...

Generating a multi-dimensional array from a one-dimensional array - Structuring Data

Looking to create a nested array utilizing the path as a guide for child elements. For example, 4.1 is a child of 4, 4.1.1 is a child of 4.1, and so on. Given a flat array with all data and paths, what's the optimal method to construct a nested array ...