How can you generate a dynamic array using TypeScript?

I am facing a challenge with an array provided below.

let arr = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},
           {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19134592970", _sport: "Soccer"},
           {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+191767542970", _sport: "Soccer"},
           {_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+191723422970", _sport: "Soccer"},
           {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+18767692970", _sport: "Soccer"}];

I am looking for a solution where I can compare all objects in the array and extract similar ones into separate arrays dynamically.

For instance, considering the first 3 objects in the array above, if they have the same selectedDate, slot, and sport, I want them to be grouped together in a new dynamic array. The last 2 objects are different from the first 3 as they have different dates (selectedDate). Here is how I want the dynamic arrays to look like:

arr1 = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},
        {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19145692970", _sport: "Soccer"},
        {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177612370", _sport: "Soccer"}];

arr2 = [{_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+191776639270", _sport: "Soccer"},
        {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19100692465", _sport: "Soccer"}];

I need assistance on achieving this through creating dynamic arrays. Can anyone provide guidance on how to accomplish this? Thank you.

Answer №1

To group by keys, you can utilize the reduce function.

let arr = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},           {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"}];
           
let result = arr.reduce((a, c) => {
  let groupKey = ['_selectedDate', '_slot', '_sport'].map(g => c[g]).join('|');
  (a[groupKey] || (a[groupKey] = [])).push(c);  
  return a;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

"Handling dependency injection with cyclic dependencies along with a custom implementation of HTTP and ConfigService

I am currently working on implementing a ConfigService to retrieve the appropriate configuration for each environment within the project. However, I have run into an issue with cyclic dependencies. (index):28 Error: (SystemJS) Provider parse errors: C ...

Tips for implementing the data.map function in Reactjs

I am currently exploring Reactjs with nextjs, and I am facing an issue with fetching data using the "map" function. Can anyone provide guidance on how to approach this? Below is my current code snippet: import { useEffect, useState } from "react" export ...

Arranging array based on the sequence of another array

There are two arrays that I am working with: Main array: const items = [ "Лопата 123", "Empty Forest", "Forever young", "My ears", "Most Important", "16 Tons", "Operation ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...

Error: The SpringBoot API returned a SyntaxError because an unexpected token < was found at the beginning of the JSON response

I am currently following a tutorial on Spring Boot React CRUD operations which can be found here. However, I have encountered an issue when trying to fetch JSON data from the REST API and display it in my project. Despite following the steps outlined in th ...

Issue with applying CSS properties of 'top' and 'left' to a dynamically created div using

After an extensive search on both the site and the internet, I have not had any luck so far. I am dealing with a series of dynamically-generated divs using JQuery, cloned from the original HTML source. While I can manipulate the positioning properties of ...

Using MongoDB to find a specific element in an array and then make updates

I have performed aggregation to calculate the total and the objects that contribute to the total. Now, I need to update the source table with the aggregated object ID for the elements involved in the aggregation, establishing a two-way relationship. col ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

Exploring the dynamic relationship between React's useEffect and useState functions

Currently, I am working on developing a table using React and Material UI's XGrid component. The table includes buttons that execute specific actions when clicked. One of the requirements is to set the row ID upon clicking the row itself using the use ...

What is the best way to retrieve the most recent emitted value using a BehaviorSubject in a different component?

When using BehaviorSubject, I encounter an issue where I can get the last emitted value in the same component, but after navigating to another component, I only receive the default value instead of the last emitted value. I implemented BehaviorSubject to ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

Having trouble obtaining the serialized Array from a Kendo UI Form

I am working on a basic form that consists of one input field and a button. Whenever the button is clicked, I attempt to retrieve the form data using the following code: var fData = $("#test").serializeArray(); Unfortunately, I am facing an issue where I ...

What causes the issue of undefined destructured environment variables in Next.js?

Within my application built with Next.js, I have configured a .env file containing a variable labeled API_KEY. When attempting to destructure the value of this variable, I am consistently met with undefined, as shown below: const { API_KEY } = process.env ...

Advancing in the world of three.js

var leftKey = 72; var rightKey = 74; document.onkeydown = checkKey; function checkKey(e){ e = e || window.event; if(e.keyCode === leftKey){ car.position.z = car.position.z -10; } if(e.keyCode === rightKey){ ...

Implement a mouseenter event to all input elements that have specific names stored in an array, utilizing jQuery

I'm struggling to figure out how to apply my function to all input elements with a name that is included in my array. This is what I've attempted so far: var names = ["name1", "name2"]; $(document).ready(function(){ $('input[name=names[ ...

What prevents me from displaying the image in the Bootstrap tooltip?

I am currently utilizing the Bootstrap framework v3.3.0 for my website. I'm trying to implement an image as a tool-tip when the user hovers their mouse pointer over an icon. Here is the HTML code I have: <div class="col-sm-5"> <div class= ...

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Tips for customizing the appearance of date and time formats

Does anyone know how to retrieve this specific time format using Angular2 TypeScript? 2016-9-25T05:10:04.106Z I've tried searching online but couldn't find a straightforward solution. When attempting this in TypeScript, the following results a ...

Ways to initialize a double pointer with a single pointer

Recently, I came across an interesting code snippet that deals with handling multiple pipes in C: int main() { char *ls[] = {"ls", NULL}; char *grep[] = {"grep", "pipe", NULL}; char *wc[] = {"wc", NULL}; char **cmd[] = {ls, grep, wc, NULL}; loo ...