C # Linq SelectMany, TypeScript Equivalent

Viewed 1502

How can I write SelectMany, which is a Linq function in C#, to do the same in TypeScript language.

For Example, The output of the sample code is as follows:

string[] letter = { "a", "b", "c" };
int[] number = { 1, 2, 3 };
var result = letter.SelectMany(x => number, (x, y) => (x + y));

result = a1, a2, a3, b1, b2, b3, c1, c2, c3

How can I write the typescript equivalent of this code. I try this but it doesn't work.

const result = letter.reduce((x, y) => [...x, ...y], number);

Can you help me, Thanks.

2 Answers

C# SelectMany corresponds to Typescript's flatMap, scala's flatMap and haskell's bind. Idea comes from concept called Monad from category theory.

With flatMap

const letters: string[] = ['a', 'b', 'c']
const numbers: number[] = [1, 2, 3]
const result = letters.flatMap((letter) => numbers.map((n) => `${letter}${n}`))

console.log(result)
// OUTPUT
// [
//   'a1', 'a2', 'a3',
//   'b1', 'b2', 'b3',
//   'c1', 'c2', 'c3'
// ]

With reduce

const letters: string[] = ['a', 'b', 'c']
const numbers: number[] = [1, 2, 3]
const result = letters.reduce<string[]>((p, c) => [...p, ...numbers.map((n) => `${c}${n}`)], [])

console.log(result)
// OUTPUT
// [
//   'a1', 'a2', 'a3',
//   'b1', 'b2', 'b3',
//   'c1', 'c2', 'c3'
// ]

There is a TypeScript library for LINQ.

It is called ts-generic-collections-linq.

Providing strongly-typed, queryable collections such as:

  • List
  • Dictionary

Easy to use.

NPM

https://www.npmjs.com/package/ts-generic-collections-linq

Sample linq query:

let result = ownerPets.selectMany(x => x.pets);
Related