Combining two arrays into one with the .map and .filter methods

When using two selects on a database, I am retrieving two arrays named "Movies" and "Comments". My goal is to merge these arrays based on their "movieId" and send the combined array back to the client in the response.

Movies:

[
    {
        "movieId": "0DD20C53-FF5C-EB11-8140-707781834352"
    },
    {
        "movieId": "01C14AF4-3E37-EB11-8138-778184434310"
    }
]

Comments:

[
    {
        "commentId": "1",
        "movieId": "0DD20C53-FF5C-EB11-8140-707781834352",
        "content": "thanks"
    }
]

The desired outcome should look like this:

[
      {
        movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
        comments: [
          {
            commentId: "1",
            movieId: "0DD20C53-FF5C-EB11-8140-707781834352",
            content: "thanks",
          }
        ]
      },
      {
        movieId: "01D14A24-3E37-EB11-8118-778155534314",
        comments: []
      }
]

I have written the following code snippet, but there seems to be an issue as the comment is added to both movies. There might be an error with checking if the movie.movieId matches comment.movieId. Can someone guide me on how to correctly use .map and .filter or suggest a better solution for this scenario? Perhaps there is a more performance-efficient way.

let result = movies.map((movie) => ({
      ...movie,
      comments: comments.filter((comment) => {
        return comment.movieId === movie.movieId;
      })
    }));

Answer №1

Ensure you update = to === for string comparison. Additionally, include a return statement:

const result = movies.map(movie => ({
  ...movie,
  comments: comments.filter(comment => {
    return comment.movieId === movie.movieId;
  }),
}));

In summary:

const result = movies.map(movie => ({
  ...movie,
  comments: comments.filter(comment => comment.movieId === movie.movieId),
}));

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

Is the boolean condition in my Angular template not updating properly when the state changes?

I am attempting to modify a template when a specific pie chart slice is clicked. Here is the template code: <h1>{{slice && slice.name}}</h1> <h1>{{slice && slice.value}}</h1> Check out this demo: https://st ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Tips for directing your attention to an input field in Angular

I'm struggling to find a simple solution for setting focus programmatically in Angular. The closest answer I found on Stack Overflow is about dynamically created FormControl, but it seems more complex than what I need. My situation is straightforward ...

Sending VSCode to external functions

My primary entrypoint containing the activate() function is: extension.ts import * as vscode from "vscode"; import { subscribe } from "./eventListeners.ts"; export function activate(context: vscode.ExtensionContext) { vscode.command ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

Tips for transforming alphanumeric characters into value ranges using Typescript

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"]; // code snippet to create expected string: "AB01-AB04, AB11, BC12-BC13, SB33" The array contains combinations of one or two letter characters followed by two or three digits. Examples ...

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

Learn how to retrieve the return data from two combined objects using Angular's TypeScript syntax

I've encountered an issue with TypeScript syntax, specifically when a WebAPI returns a DTO containing two objects. The object being returned looks like this: { "userList": [{ "id": 1, "firstNm": "John", "lastNm": "Doe" }, ...

Navigating to a different page rather than a component in Angular

I have a question about routing in Angular. Can I navigate to a page that is within the same component or in a different directory? For example, if we are currently in the component home: home home.component.html home.component.css home.component.ts cl ...

What is the syntax for declaring a variable with multiple types in Angular/Typescript?

Imagine having a variable declared with the following type: test?: boolean | { [key in TestEnum ]: boolean }; Now, let's assign this test variable within a constant where it can hold either a boolean value or a mapping to an enum. Consider the exampl ...

Navigating in Angular is made easy with the Angular routing feature, which allows you to redirect

I have been working through the Angular Tour of Heroes Guide and encountered the section on the "default route". I decided to experiment by removing the pathMatch attribute from the Route associated with an empty string. Below is the code snippet in quest ...

What is the best way to apply a unique style to the currently active tab in a sidenav based on

I am in the process of creating a side navigation bar where I want to incorporate a left border on the active tab. How can I achieve this by utilizing state and passing a boolean value as a prop to the Child SideNavItem class, then updating it with each ta ...

Using the angular2-cookie library in an Angular 2 project built on the rc5 version

Starting a new angular2 rc5 project, I wanted to import the angular2 cookie module. After installing the module with npm, I made changes to my angular-cli-build.js file : npm install angular2-cookie edited my angular-cli-build.js file : module.exports ...

The declaration of 'tabs: TabsProps[] | undefined;' is not compatible with the type 'IntrinsicAttributes & TabsProps'

Can someone help me with creating a custom tab view component using the latest version of ant design? I'm not sure if I need to add Tabpane separately or if it comes included in the 'Tabs' component. Here's my code : import { Tabs } fr ...

Compiling an Angular project with an external library in AOT mode using angular-cli is causing issues and not compiling successfully

Embarking on a fresh new project, I utilized angular-cli 8.1.2 for the generation process. The goal is to establish a shared library that caters to multiple microservices (apps). This particular library should remain separate from the applications folder, ...

What is the method for updating a 'Signal' within an 'Effect'?

Working with signals in Angular 17, I encountered an issue while trying to update the value of a signal. The error message that I received is as follows: NG0600: Writing to signals is not allowed in a `computed` or an `effect` by default. Use `allowSignalW ...

Typescript doesn't seem to recognize window.location.href

I am currently working on implementing a logout feature in my application. I initiate a call to the /logout web service and receive a URL as a response. I then use this URL to redirect my page accordingly. Below is the code snippet: constructor( $q: ng. ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

What is the process for injecting an asynchronous dependency with inversify?

I am currently working on a TypeScript application and utilizing Inversify for Inversion of Control (IoC). Within my codebase, there is a connection class defined as follows: 'use strict'; import { injectable } from 'inversify'; impor ...