What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' argument as a string to return string[]? If I just use 'string' instead of keyof T, TypeScript throws an error because it can't identify property in the unknown type on the line item[property].


interface IMovie {
  genre: string[];
  actors: string[];
}

const movies: IMovie[] = [
  {
    genre: ['Action', 'Sci-Fi', 'Adventure'],
    actors: ['Scarlett Johansson', 'Florence Pugh', 'David Harbour'],
  }
];

function collectByProperty<T>(arr: T[], property: keyof T): string[] {
  const array = arr.map((item) => item[property]).flat();
  const elem = array[0];
  const final = [...new Set(array)];
  return final;
}
const genres = collectByProperty<IMovie>(movies, 'genre');
const actors = collectByProperty<IMovie>(movies, 'actors');

console.log(genres);
console.log(actors);

I attempted to create a variable within the function body and assign the property to it.

Answer №1

Opt for flatMap over map followed by flat:

let array = arr.flatMap((element) => element[property]);

Answer №2

It is important to ensure that the array in your collectByProperty function is flattened, as it initially generates a nested array structure (for example:

[['Action', 'Sci-Fi'], ['Drama']]
). By flattening this array, you will transform it into a one-dimensional array (['Action', 'Sci-Fi', 'Drama']), aligning with the desired output.

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

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Retrieve error messages from API while utilizing Next-auth

Is it possible for Next-auth to handle API errors and pass them to the client-side? For example, our mobile app successfully handles API responses indicating incorrect email or password. However, on our website using Next-auth, we want to modify the retur ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

Tips for linking two project routes in NodeJS and incorporating React (I am interested in invoking React within the NodeJS project)

I'm in the process of linking two projects, one using reactJS and the other NodeJS. Currently, NodeJS is running smoothly on localhost:3000. Next, I want to call a React application which redirects to port localhost:3001. How can I seamlessly connect ...

Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects. var allQuestions = [{ "question": "Who was Luke's wingman in the battle at Hoth?", "choices": ["Dak", "Biggs", "Wedge", ...

Creating a standalone executable for Node.js without including the entire Node.js framework

Trying to pack a simple hello world script into an executable has led to some challenges. Both pkg and nexe seem to include the entirety of Node.js in the output file, resulting in quite larger files than necessary (around 30 MB). Although EncloseJS was fo ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

Sending information to a VueJS component

Hey there! I have a challenge in VueJS where I need to transfer Firebase Authentication user data (JSON) from the App.vue component to another component named Details.vue. The goal is to display the name of the logged-in user on Details.vue. In App.vue: ...

What is the best way to convert a graphql query into a JSON object?

I'm facing an issue where I need to convert a GraphQL query into a JSON object. Essentially, I have a query structured like the example below, and I'm seeking a method to obtain a JSON representation of this query. Despite my efforts in searching ...

Utilizing Node Js for Form Data Transmission and Retrieval

I've successfully created two separate JS files, each responsible for sending and retrieving form data to and from the database. My dilemma is whether it's more practical or feasible to leave these two JS files as they are and serve their individ ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward: class MyController extends Controller { public function list() { return response()->json(['a' => 'hello']); } } When I access the ...

Utilize a generic approach for every element within a union: Transforming from Some<1 | 2 | 3> to individual Some<1>, Some<2>, or Some<3> instances

As I was unable to create a concise example for my issue, this is a general rendition of it. I am facing a scenario where the "sequence of application" is vital in nested generics. type Some<A> = {type: A} type Union1 = Some<1 | 2 | 3> type Uni ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...