Tips for leveraging _.union function from lodash to eliminate duplicate elements from several arrays in a TypeScript project

I attempted to use import _ from 'lodash-es' and

_.union(user.users.map(user => user.city))
. However, the result was not as expected, such as:
["city_id1", "city_id2", "city_id3", "city_id4"]

What is the correct way to utilize _.union, or is there a better method to flatten all arrays and create a unique array?

### data
const user =
{
  "users": [
    {
      "id": "user_id1",
      "city": ["city_id1", "city_id2"]
    },
    {
      "id": "user_id2",
      "city": ["city_id3", "city_id4"]
    },
    {
      "id": "user_id3",
      "city": ["city_id1", "city_id3"]
    },
    {
      "id": "user_id4",
      "city": ["city_id2", "city_id4"]
    }
   ]
}

Answer ā„–1

If you want to achieve the desired outcome, you can leverage the power of Set along with flatMap.

Here's a concise one-liner solution:

const result = [...new Set(user.users.flatMap((o) => o.city))];
console.log(result);

const user = {
  users: [{
      id: "user_id1",
      city: ["city_id1", "city_id2"],
    },
    {
      id: "user_id2",
      city: ["city_id3", "city_id4"],
    },
    {
      id: "user_id3",
      city: ["city_id1", "city_id3"],
    },
    {
      id: "user_id4",
      city: ["city_id2", "city_id4"],
    },
  ],
};

const set = new Set(user.users.flatMap((o) => o.city));
const arr = [...set];
console.log(arr);

Answer ā„–2

if you're still interested in utilizing lodash

then here's the solution


const person =
{
  "people": [
    {
      "id": "person_id1",
      "location": ["location_id1", "location_id2"]
    },
    {
      "id": "person_id2",
      "location": ["location_id3", "location_id4"]
    },
    {
      "id": "person_id3",
      "location": ["location_id1", "location_id3"]
    },
    {
      "id": "person_id4",
      "location": ["location_id2", "location_id4"]
    }
   ]
}

let b = person.people.map(entry=>entry.location)
_.union(...b)

Answer ā„–3

Loop through the users array and populate a new array unique_cities with the outcome of using _.union

var user_data =
{
  "users": [
    {
      "id": "user_id1",
      "city": ["city_id1", "city_id2"]
    },
    {
      "id": "user_id2",
      "city": ["city_id3", "city_id4"]
    },
    {
      "id": "user_id3",
      "city": ["city_id1", "city_id3"]
    },
    {
      "id": "user_id4",
      "city": ["city_id2", "city_id4"]
    }
   ]
};

var unique_cities = [];
user_data.users.forEach(user => {
  unique_cities = _.union(user.city, unique_cities);
});

console.log(JSON.stringify(unique_cities.sort()));
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83efece7e2f0ebc3b7adb2b4adb1b2">[email protected]</a>/lodash.min.js"></script>

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

Parent Component in Angular 2 Fails to Refresh Upon Observable Update

I have been utilizing an Observable service to facilitate data coordination among components. Specifically, I am attempting to utilize it for managing the visibility of various HTML elements within my application. Currently, when I toggle the behavior sub ...

Having trouble populating Extjs Grid with JSON data

In this simple grid, I am attempting to display three columns - Subject ID, Subject Name, and Subject Short Name by obtaining JSON data. The data is stored in a variable called myData in JSON format, which has been received from the server. Despite pasting ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

Using an array of strings as a key in React with TypeScript to access values from state

import React, { useState } from 'react'; interface PropsInterface { keys: string; // name,email,password } const Poster: React.FC<PropsInterface> = (props: PropsInterface) => { const [state, setState] = useState({ name: ' ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

The concept of localStorage is not recognized in the next.js framework

Currently working with next.js for frontend development. Facing an issue where I need to access user data from localStorage, but due to next.js being a server-side rendering framework, I am unable to retrieve data from localStorage. How can I solve this pr ...

The search for Javascript is futile when utilizing .Net RijndaelManaged

I have implemented an encryption/decryption process in my C# WCF using the following code: public static string EncryptString(string InputText, string Password) { RijndaelManaged RijndaelCipher = new RijndaelManaged(); RijndaelCiph ...

What is the best approach to create a regex pattern that will identify variables enclosed in brackets across single and multiple lines?

In my Typescript project, I am working on matching all environment variables that are de-structured from process.env. This includes de-structuring on both single and multiple lines. Consider the following examples in TS code that involve de-structuring fr ...

Testing the local transmission of form data via Javascript: A Step-by-Step guide

Currently studying how to send forms using JavaScript by manually creating an XMLHttpRequest. Towards the end of the provided example, there's a note: Note: If you want to send data to a third party website, keep in mind that this use of XMLHttpRequ ...

Ember application experiencing trouble displaying Facebook Like Box

Iā€™m currently facing an issue with integrating the like box into our ember app, specifically in a template named about. The problem arises when users enter the ember app from a different route, instead of directly accessing the about route. In such cases ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

Getting data from a URL using Node.js and Express: A beginner's guide

Currently, I am facing an issue with extracting the token value from the URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. My get request successfully validates the token and redirects the user to a password reset screen. Howe ...

What is the best method to retrieve a nested JSON property that is deeply embedded within

I am facing an issue with storing a HEX color code obtained from an API in a Vue.js app. The object app stores the color code, for example: const app = {"theme":"{\"color\":\"#186DFFF0\"}"}. However, when I try to access the color prope ...

Warning triggered Grunt cancellation

I've successfully installed "npm" on my local machine. When it comes to installing grunt in my Gruntfile.js directory, I follow these steps: npm install grunt npm install -g grunt-cli grunt watch Although the tasker is up and running, I en ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

Ways To Obtain Trustworthy Dates Using JavaScript

Last week, I encountered an intriguing issue at my job. I needed to obtain a date accurately using JavaScript, but the code I was working with utilized new Date() which resulted in discrepancies due to some customers having incorrect system time settings. ...

Challenges of aligning a modal overlay in the middle of mobile screens

Currently, I am developing a website and encountering a specific issue with the modal structure. When viewing it on Codepen using Chrome devtools and toggling the device toolbar to simulate mobile screens, everything appears fine. However, when opening the ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...