Locate every instance where two arrays are compared in TypeScript

My goal is to search for matches in Object 2 where the _type corresponds to filterByCallTypeTitulo in Object 1, and then create a new array including all the matched information from Object 2.

I attempted to achieve this using the filter() method and forEach, but unfortunately, I have not been successful so far (likely due to my incorrect implementation).

This is an example of what I have tried:

callDataList.filter(value => value.type === filters.voiceFilterViewModel.filterByCallTypeTitulo);

Details of Object 1 (filters.voiceFilterViewModel):

VoiceFilterViewModel {_filterByDateTime: "Duración", _filterByAscDesc: "Descendente", _arrayCallType: Array(1), _filterByCallTypeTitulo: "Internacionales"}
arrayCallType: Array(1)
0: VoiceFilterItemViewModel
callTypes: null
titulo: "Internacionales"
_callTypes: null
_titulo: "Internacionales"
__proto__: Object
length: 1
__proto__: Array(0)
filterByAscDesc: "Descendente"
filterByCallTypeTitulo: "Internacionales"
filterByDateTime: "Duración"
__proto__: Object

Details of Object 2 (callDataList):

0: DetailedUsageVoiceModel {_duration: 601, _cost: 0, _type: "Móvil Nacional", _usageDate: Moment, _usageType: "VOZ", …}
1: DetailedUsageVoiceModel {_duration: 79, _cost: 0, _type: "Móvil Nacional", _usageDate: Moment, _usageType: "VOZ", …}
2: DetailedUsageVoiceModel {_duration: 1314, _cost: 0, _type: "Numeración corta", _usageDate: Moment, _usageType: "VOZ", …}

Detailed Information on Object 2:

0: DetailedUsageVoiceModel
calledNumber: (...)
origin: (...)
startDate: (...)
trafficType: (...)
type: "Móvil Nacional"

Answer №1

It looks like you're on the right track, but there may be some missing pieces in your approach. By filtering the array, you will get a new array with only the matched items.
After that, you can iterate over the filtered items to create a new array based on them.
I'm not entirely certain if this is what you had in mind, but here's my take on it.

const matchedItems = callDataList.filter(value => value.type === filters.voiceFilterViewModel.filterByCallTypeTitulo);

const newArr = matchedItems.reduce((accumulator, item) => { 
  accumulator.push({
    "key1": filters.voiceFilterViewModel.titulo,
    "key2": filters.voiceFilterViewModel.filterByAscDesc
  }); 

  return acc;
}, []);


For more information on Array.reduce and accumulators, check out the documentation at mdn
I hope this explanation helps!

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

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

Filtering a field in AngularJS based on the elements in an array

I have an Array with a list of Id's that I need to filter my results by. For example, take a look at the code snippet below. How can I display records where the 'StatusId' matches one of the Id's in the 'ids' array? In this c ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

Using PHP to generate a table populated with generic elements from an array

How can I create a dynamic table in PHP that can handle any generic array with different keys and values, including nested arrays? I want to use the same table structure for various arrays regardless of their content. Any advice on achieving this flexibili ...

Get the HTML file converted to a DOCX format that is compatible with Mac Pages

I am currently working on a Next.js application using TypeScript, and I want to give users the ability to download a page as a DOCX file. Initially, I was excited to discover that this could be easily accomplished by following this method. However, after ...

Leverage the power of Material UI makeStyles in conjunction with Typescript

In an effort to keep things organized, I've created a specific file for the classes prop, such as MuiAlert. Is there a way to specify to makeStyles that only Alert classes should be used? The current method works, but I'm sure there's a mo ...

The incorrect argument is being used to infer the generic type

I have implemented the NoInfer feature from the library called ts-toolbelt. However, it seems that the example provided below does not reflect its intended effect. In this scenario, the generic type is deduced from the util function as soon as it is intr ...

Issue: Map container not located when implementing a leaflet map with Angular

Here is the complete error message: core.js:6479 ERROR Error: Map container not found. at NewClass._initContainer (leaflet-src.js:4066) at NewClass.initialize (leaflet-src.js:3099) at new NewClass (leaflet-src.js:296) at Object.createMap [a ...

What methods can I use to prevent a negative value from being saved in an array?

I am working on a code that accepts x and y coordinates, but I need to ensure that no negative values are stored in the array. I am having trouble avoiding storing these negative values while looping through the input. Can someone guide me on how I can a ...

Developing an asynchronous function to retrieve data from an external API utilizing Await/Async strategy

Currently, there is a method under development that retrieves a value from the API. What steps are needed to properly integrate Async/Await functionality into this process? fetchAccountById(){ let accountName; this.accountService.fetchDa ...

Error encountered during the conversion process from Collection to array: ClassCastException

I'm currently working on a project where I need to convert a given Collection into an array. Here is the code I have so far: public class InsertionSorter< T extends Comparable<T>> { private T[] array; @SuppressWarnings("unchecke ...

Is it possible to achieve pagination by simply dragging the scroll bar to the top or bottom position?

Recently, I've been working on implementing a pagination function for a list of items. The pagination currently works well with scrolling events - it automatically moves to the next page when scrolling to the bottom, and to the previous page when scro ...

TypeScript 1.6 warning: Component XXX cannot be instantiated or called as a JSX element

var CommentList = React.createClass({ render: function () { return ( <div className="commentList"> Hello there! I am the CommentList component. </div> ); } }); var ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...

Has the GridToolbarExport functionality in Material UI stopped working since the latest version update to 5.0.0-alpha.37?

I have created a custom toolbar for my Data Grid with the following layout: return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensitySelector /> <Gr ...

Form a matrix using a string

If we have a string s = "1 2\n3 4", our objective is to create a matrix $ \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} $ Here is the code snippet : public static String[] buildFrom(String s) { Stri ...

The graph generated with NumPy and matplotlib does not show certain data points

Considering the given code designed for Monte Carlo integration of a function f, I am intrigued by what would occur if I were to define f as y = sqrt(1-x^2), representing a unit quarter circle, and specify an endpoint greater than 1. This is intriguing bec ...

The script type `(close: any) => Element` cannot be assigned to type `ReactNode`

Encountering a problem while adding a popup in my TypeScript code Error: Type '(close: any) => Element' is not compatible with type 'ReactNode'. <Popup trigger={ <button className="fixed bott ...

Encountered an issue in Angular 6: Unable to access property '0' of undefined

There's an error popping up in the console saying, Cannot read property '0' of undefined, but surprisingly I'm still getting the expected result. Below is my HTML code snippet: <div class="col-md-3"> <div class="slider-prod ...