Guidelines on creating a recursive function in Typescript that calculates the common elements between multiple arrays of strings

I have a code snippet that calculates the intersection of multiple arrays of strings.

Play with Typescript here

export const findIntersection = (list1: string[], list2: string[], ...otherLists): string[] => {
  const result = [];

  for (let i = 0; i < list1.length; i++) {
      const item1 = list1[i];
      let found = false;
      
      for (let j = 0; j < list2.length && !found; j++) {
          found = item1 === list2[j];
      }
      if (found === true) {
          result.push(item1);
      }
  }

  if (otherLists.length) {
    return findIntersection(result, otherLists.shift(), ...otherLists);
  } else {
    return result;
  }
};

While this function works well in JS, I am facing some challenges while converting it to Typescript. Specifically, I'm struggling with typing the ...otherLists parameters.

The error message I'm receiving is as follows:

https://i.sstatic.net/vGS9B.png

Answer №1

This is the way to write it out:

const findIntersection = (array1: string[], array2: string[], ...moreArrays: string[][]): string[] => {

  const commonElements = [];

  for (let i = 0; i < array1.length; i++) {
      const element1 = array1[i];
      let matchFound = false;
      
      for (let j = 0; j < array2.length && !matchFound; j++) {
          matchFound = element1 === array2[j];
      }
      
      if (matchFound) {
          commonElements.push(element1);
      }
  }

  const nextArray = moreArrays.shift();
  
  if (nextArray) {
    return findIntersection(commonElements, nextArray, ...moreArrays);
  }

  return commonElements;
};

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

Using the syntax (char*)(void*) works within the main program, but it fails when used in

I have an array of items called nodes. Each node has a field containing a void pointer. Within a function, I take a specific node and assign the void pointer to a string, which represents a decimal converted to binary. The problem arises when attempting ...

Transforming various arrays into the insert_batch style of CodeIgniter

I'm working on creating a multi-lingual form using CodeIgniter. Here is the structure of my POST array: Array ( [title] => Array ( [en] => English Title [de] => German Title ) [url] => Array ( [en ...

My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCoun ...

What causes the select dropdown to display an empty default in Angular 8 following an HTTP request?

I have created a simple HTML code to populate array elements in a dropdown list, with the default value being fetched from an HTTP service during the ngOnInit lifecycle hook. However, I am encountering an issue where the default value is displayed as empty ...

Is there a way to code this so that it can read a file with a variable number of lines?

import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Process_TCPProbe_dm{ public static void main(String[] args) throws IOException { //Ex ...

What is the best approach for implementing recursion within a foreach loop in TypeScript?

Problem Situation I am attempting to develop a customized typewriting effect similar to the one demonstrated here with a 100ms delay using Angular. The TypeScript code I have written for this purpose is as follows: private arr: string[] = ["Lead Dev ...

Different approach in C++ instead of switch statement

I have around 40 cases in a switch statement. The input being checked is a number formed by concatenating two user inputs. For example, if the user enters 3 and 4, the switch statement receives 34 as the value to check. Each case in the switch statement th ...

What is the reason behind the occurrence of `(User & { _id: Schema.Types.ObjectId; }) | null` when calling findById?

Today marks my debut using typescript and mongoose. Here's a glimpse of what I've worked on. Type export interface User extends Document { _id: ObjectId; lastName: string; } Schema const userSchema = new Schema<User>({ lastName: { t ...

"Enhance your PrimeVue Tree component with interactive action buttons placed on every TreeNode

Details: Using Vue 3.3.6 in composition API script setup style Utilizing PrimeVue 3.37.0 and PrimeFlex 3.3.1 Implemented with Typescript Objective: To create a tree structure with checkboxes that are selectable, along with action buttons on each TreeNod ...

Attempting to develop a Java array with a well-defined structure

I'm striving to develop a program similar to the following: int points = 250; public class point { float x, y; } point[] p = new point[points]; // constructor public JavaMain() { Random r = new Random(); for (int i = 0; i < poin ...

What is the best way to integrate database information into the array shown below?

Is there a way to populate the array with data from the database without any issues? I've attempted various methods but have been unsuccessful so far. I am looking to store database values in an array structure class topsis { public $alternatif = arr ...

What is the method for obtaining the dynamic key of an object?

Is there a way for me to access the value of record.year dynamically? It seems like using record["year"] should give me the same result. I am trying to make my chart adaptable to different x-y axis configurations, which is why I am using fields[0] to retr ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

Error: Unable to access the 'registerControl' property of the object due to a type mismatch

I'm struggling to set up new password and confirm password validation in Angular 4. As a novice in Angular, I've attempted various approaches but keep encountering the same error. Seeking guidance on where my mistake lies. Any help in resolving t ...

Is it possible for a compound literal to provide both accurate results and nonsense when assigned to an array pointer simultaneously?

#include <stdio.h> int main(void) { int array[5], *ptr, index; ptr = array; ptr = (int []){1, 2, 3, 4, 5}; for (index = 0; index < 5; index++, ptr++) { printf("%d == %d\n", *ptr, a[index]); } return 0; } Beho ...

Tips on showcasing Java map information obtained from the backend on an Angular/Typescript interface

I have a 'detailsMap : any' variable from the backend that contains multiple rows in the format (key1,key2). I need to display this data in the UI using TypeScript/Angular2. Please advise on how I can achieve this. key1 : { Name:'ABC' , ...

Retrieving the value of an object using an array of keys

Consider the following object: const obj = { A:{ a1:'vala1', a2:'vala2' }, B:{ b1: 'valb1', b2: 'valb2' }, C:{ c1:{ c11:'valc11' }, c2:'valc2' } } We also have an array: const ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

The getAuth() helper found in the api directory's Clerk retrieves the following data: { userId: null }

I'm completely stuck here.. Currently working with the clerk and I am looking to access the userId of the current user using the getAuth() helper. For more information, refer to the docs: pages/api/example.ts import { getAuth } from "@clerk/n ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...