the process of combining arrays within an array in Angular

Is there a way to combine arrays of arrays in Angular?

const b: any = [];
b.push(
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }
  ],
  [{ date: "2019-12-20 08:08:00" }, { date: "2019-10-20 08:08:00" }],
  [{ date: "2019-12-20 08:08:00" }, { date: "2019-12-30 08:08:00" }]
);
uniq(flatten(b, true), true, item => item.date); //error here

Error: Expected 1 argument, but received 3.

Also, how can duplicates be removed using Lodash uniqBy function?

Expected result:

[
    "2019-12-21 08:08:00",
    "2019-12-20 08:08:00",
    "2019-12-30 08:08:00"
]

Answer №1

If you're looking to achieve this, you can utilize the Underscore - uniq function along with the flatten function.

const arr: any = []; arr.push(   [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }   
   ],
   [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-10-20 08:08:00" }
   ],
   [
    { date: "2019-12-20 08:08:00" }, 
    { date: "2019-12-30 08:08:00" }
   ] );
_.uniq(_.flatten(arr, true), true, item => item.date)

Here is the resulting array:

[{date:"2019-12-20 08:08:00"},
{date:"2019-12-21 08:08:00"},
{date:"2019-10-20 08:08:00"},
{date:"2019-12-30 08:08:00"}]

If you prefer using lodash, you can achieve the same result with the following code:

_.uniqBy(_.flatten(arr, item => item.date), 'date')

Answer №2

If we want to work with vanilla JavaScript, the necessary components are:

  • Map for obtaining unique items from an array
  • flatMap method for flattening an array
  • Array.from to create an array from a Map collection

The code implementation would look like this:

const result = new Map(b.flatMap(s => s).map(a => [a.date]));
let uniques = Array.from(result.keys());

Here's an example:

const b = [];
b.push(
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }
  ],
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-10-20 08:08:00" }
  ],
  [{ date: "2019-12-20 08:08:00" },
  { date: "2019-12-30 08:08:00" }]
);

const result = new Map(b.flatMap(s => s).map(a => [a.date]));
console.log(Array.from(result.keys()));

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 with injecting string HTML into the head section in NextJS?

We have incorporated a NextJS page with a headless CMS platform. Within this content management system, I have included an option for the administrator to save custom code snippets to be inserted either in the head section or at the end of the body. In m ...

Each time a click is made, an Uncaught TypeError occurs, indicating that it is unable to read properties from an undefined source (specifically

I have successfully built my React website but I am encountering a console error that I am trying to resolve. Each click on the page triggers the following error: Uncaught TypeError: Cannot read properties of undefined (reading '0') at Array. ...

Determine the difference between dates using Angular 2's array filtering function

Here's a way to get the current time in seconds: let currentTimeInSeconds = new Date().getTime() / 1000; I have an array containing objects with an expirationDate property that returns expiration time in seconds. I can find the bills that have expir ...

Encountering a problem with ResolverFactory injection while trying to inject a resolver

As a newcomer to programming, I decided to create my own Resolver class and integrate it into my feature module. However, I encountered the following error message: core.js:4352 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(CivilSt ...

The Zoom-sdk functions properly on a local machine, but encounters issues when it is

Using zoom's API, jwt, and the websdk, I am able to create a meeting on button click, join as a host, and start the meeting for others to join. This process works flawlessly when running locally, but once deployed to Cloudflare, I encounter the follow ...

Implement validation within the child component using Reactive Forms

In this demonstration, a reactive form has been created with an input field placed inside a child component. The goal is to add a new form control within the child component and perform validation on it within the same component. However, an error has been ...

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

Explore all Intellisense choices for Typescript Props in VS Code effortlessly

In my experience, I've noticed that to see intellisense options for a TypeScript type in VS Code, you have to start typing the attribute name. If you type "a", you'll only see options that contain "a" and nothing else. Take a look at this scree ...

Angular does not allow the transfer of property values from one to another

As of late, I have delved into learning Angular but encountered an issue today. I have the following Component: import { Component, OnInit } from '@angular/core'; import { SharedService } from '../home/shared.service'; import { IData } ...

What is the method for inserting line breaks in Ionic2 toasts using HTML?

Is there a way to include new lines and other HTML tags in a toast message? let toast = this.toastCtrl.create({ message: "First line<br />Second line.", duration: 5000, dismissOnPageChange: true }); toast.present( ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Leverage tsconfig.json within the subfolders located in the app directory during Angular build or ng-build process

In our Angular project, I am attempting to implement multiple tsconfig.json files to enable strictNullChecks in specific folders until all errors are resolved and we can turn it on globally. I have been able to achieve this functionality by using "referen ...

Testing NextJS App Router API routes with Jest: A comprehensive guide

Looking to test a basic API route: File ./src/app/api/name import { NextResponse } from 'next/server'; export async function GET() { const name = process.env.NAME; return NextResponse.json({ name, }); } Attempting to test ...

Live server code does not update with changes made in Angular

https://i.stack.imgur.com/Yo6Y8.png In the screenshot above, you can see my changes. I simply modified the text to read Download PDF, replacing what was there previously. Instead of the folder shown here, I used the code from this compiled file: https:// ...

Angular 5 routing is reporting that the queryParams list is currently empty

Having just started with Angular, I've encountered an issue that I can't seem to solve. When passing parameters to the router (using the Router class), the list of parameters on the target site is empty. let navigationExtras: NavigationExtras ={ ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...

Unleashing the Power of RxJS with OR Conditions

I am working with two Observables. For instance, I am waiting for either an HTTP POST call or a WebSocket call to return so that I can proceed. Once either call returns, I need to verify the information until a certain condition is met. In the following e ...

Employing angular-ui-bootstrap to display pop-up notifications

I am new to using Angular and TypeScript and I am attempting to create a popup when an image is clicked. I came across a post on Stack Overflow that provides a solution using IMODALSERVICE. How to utilize angular-ui-bootstrap modals with TypeScript? Howe ...

Deactivating attribute inheritance / configuring component settings with script setup and Typescript

Is there a way to disable attribute inheritance for a component's options when using script setup syntax with Typescript in Vue 3? Here is the JavaScript code example: app.component('date-picker', { inheritAttrs: false, // [..] }) How ...

Dealing with Cross-Origin Resource Sharing problem in serving static images on Dotnet Core 3.1

I have my dotnet core 3.1 API hosted with Angular on a different domain than my frontend HTML site. I am using a jQuery watermark plugin to add watermarks to my images, but sometimes the image displays normally without the watermark being added. Upon check ...