#9898Medium

Appear only once

Find the elements in the target array that appear only once. For example:input: `[1,2,2,3,3,4,5,6,6,6]`,output: `[1,4,5]`. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement FindEles<T> which filters a tuple to only include elements that appear exactly once in the array.

Challenge Instructions: Appear only once

Medium

Find the elements in the target array that appear only once. For example:input: [1,2,2,3,3,4,5,6,6,6],output: [1,4,5].

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<FindEles<[1, 2, 2, 3, 3, 4, 5, 6, 6, 6]>, [1, 4, 5]>>,
  Expect<Equal<FindEles<[2, 2, 3, 3, 6, 6, 6]>, []>>,
  Expect<Equal<FindEles<[1, 2, 3]>, [1, 2, 3]>>,
  Expect<Equal<FindEles<[1, 2, number]>, [1, 2, number]>>,
  Expect<Equal<FindEles<[1, 2, number, number]>, [1, 2]>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Includes<T extends any[], V> = T extends [infer First, ...infer Rest]
  ? Equal<First, V> extends true
    ? true
    : Includes<Rest, V>
  : false
 
type FindEles<T extends any[], Seen extends any[] = []> = T extends [infer First, ...infer Rest]
  ? Includes<Rest, First> extends true
    ? FindEles<Rest, [...Seen, First]>
    : Includes<Seen, First> extends true
      ? FindEles<Rest, Seen>
      : [First, ...FindEles<Rest, Seen>]
  : []

How it works:

This challenge helps you understand recursive tuple filtering with auxiliary tracking state, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge