Find the distinct values from an array of objects containing varying elements using Typescript

My array contains dynamic elements within objects:

[
    {
        "Value1": [
            "name",
            "surname",
            "age"
        ],
        "Value2": [
            "name"
        ],
        "Value3": [
            "name",
            "age"
        ]
    },
    ...
]

I am trying to consolidate the values from different keys into a single object as follows:

{
        "Value1": [
            "name",
            "surname",
            "age",
            "hoursWorked",
            "timeSpent"
        ],
        ...
}

I have attempted using array.reduce() without success due to the dynamic nature of the elements. Any assistance in solving this problem would be greatly appreciated.

Answer №1

My approach involved utilizing nested for loops:

var data = [
    {
        "Value1": [
            "name",
            "surname",
            "age"
        ],
        "Value2": [
            "name"
        ],
        "Value3": [
            "name",
            "age"
        ]
    },
    {
        "Value2": [
            "name",
            "age"
        ],
        "Value3": [
            "surname",
            "name"
        ]
    },
    // Additional data objects...
];

var finalObject = {};
data.forEach(entry => {
for(var key in entry){
if(!finalObject[key]){
finalObject[key] = [];
}
entry[key].forEach(value => {
if(finalObject[key].indexOf(value) == -1){
finalObject[key].push(value);
}
})
}
});

console.log(finalObject);

Answer №2

Give this a shot:

// Create an object to hold the final result
let finalResult = {};

// Loop through the initial array 
data.forEach(object => {

  // Iterate over key value pairs
  for (let key in object) {

    // Check if key is not already in finalResult, and initialize with empty array
    if (!finalResult[key]) {
      finalResult[key] = [];
    }

    // Loop through the second level array
    for (let value of object[key]) {
      // Add value to the array if it's not already present
      if (finalResult[key].indexOf(value) == -1) {
        finalResult[key].push(value);
      }
    }
  }

});

See a demonstration here: https://stackblitz.com/edit/typescript-nzefuq?file=index.ts

Answer №3

To simplify this process and eliminate duplicates, you can utilize the reduce method along with a new Set in JavaScript.

var source = [
    {
        "Value1": [
            "name",
            "surname",
            "age"
        ],
        "Value2": [
            "name"
        ],
        "Value3": [
            "name",
            "age"
        ]
    },
    // Additional data entries here
]

var result = source.reduce((acc, val) => {
  Object.keys(val).forEach(key => {
    acc[key] = acc[key] ? [...new Set(acc[key].concat(val[key]))] :  val[key];
  })

  return acc;
}, {})

console.log(result)

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

Issues with Font Awesome fonts failing to load after compiling an Angular project using `ng build`

I've encountered an issue with Angular 8 and Font Awesome icons. I initially added the font-awesome path in the angular.json as follows: "./node_modules/font-awesome/css/font-awesome.css" However, all the icons were displaying as empty boxes (not lo ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Using the `npm install -g @angular/cli` command will not actually install the Angular CLI

I've set out to create a sample Angular2 web app, starting with the installation of Node.js (v 7.1.0) and NPM (v 3.10.9). However, when I try to install Angular CLI by executing 'NPM install -g @angular/cli' in the system command prompt, I e ...

When utilizing React and Expressjs to upload a file through REST, the request seems to stall indefinitely

Seeking assistance with a simple React page containing a form for file selection and submission. The file is uploaded to the server via a POST request using axios. Here's the code snippet for the client-side: import React, { useState } from "reac ...

Challenges with dividing input into array indices in C programming

Currently, I am diving into the world of C programming and facing an issue with splitting a string of text. My goal is to prompt the user to input multiple words separated by spaces in a single line, and then have the program split these words and store ...

Using a looping mechanism to store strings in a list, followed by outputting the contents of the

I have created a program that prompts the user to input multiple strings in a loop. The loop should break when the user enters "stop" and then print out all the entered strings with a comma after each word. For instance, if the user inputs "first", "second ...

Unable to utilize vue-cookies library in TypeScript environment

I have integrated vue-cookies into my app in the main.ts file: import VueCookies from 'vue-cookies'; ... const app = createApp(App) .use(IonicVue) .use(router) .use(VueCookies,{ expires: '30d', }); Despite adding the cookie v ...

Setting Angular FormControl value to null within a service

My Angular form is reactive and collects mobile numbers along with other details. Here is the code snippet: component.html <form [formGroup]="contactDetailsForm"> <ngx-intl-tel-input [cssClass]="'ngxIntlInputBorder'&quo ...

Authentication Redirect Failure when using Passport to an absolute URL

I am looking to redirect the user to a different URL with the code/token received after logging into Facebook using Passport in Express.js. app.get('/auth/facebook/callback', function (req, res, next) { var authenticator = passport.authentic ...

Regular expressions are effective tools, but they may not be as functional within an

Trying to validate URLs using a regex has been tricky. The regex I have works perfectly fine on regex101.com, but for some reason it keeps failing validation when implemented in my Angular field. I'm at a loss as to how to tweak it so that Angular wil ...

Encountering an error with "unexpected token import" while utilizing localize-router in an Angular 4

I am currently working on building an Angular 4 app with server-side rendering and language-specific route paths. I am using Angular CLI version 1.5.0-rc1 for this project. While everything seems to be functioning fine, I am facing a problem with incorpor ...

What is the best way to combine index signatures with established properties?

Imagine a scenario where an interface has certain defined properties with specific types, but can also include additional properties with unknown keys and various other types. Here is an example: interface Bar { size: number; [key: string]: boolean | s ...

You can only use a parameter initializer within the implementation of a function or constructor

I recently started learning TypeScript and am currently using it for React Bricks. I've been working on rendering a 3D object with three.js, but I keep encountering the error mentioned above. I've attempted various solutions such as passing color ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

What is the best method to trigger a bootstrap modal window from a separate component in Angular 8?

I have successfully implemented a bootstrap modal window that opens on a button click. However, I am now facing difficulty in opening the same modal window from a different component. Below is the code I have tried: <section> <button type=&quo ...

Using ngIf to locate a substring

<ul class="list-group" *ngFor="let head of channelDisplayHeads"> <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1"> <strong>{{ head }}</strong> ...

Opt for Readme display over index.html

I'm just starting out and I have a question about Github: Is there a way to build a page using the index.html file within a folder instead of the readme file? I've successfully built many pages where the index file is not located in a folder. Ho ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...