How to build an array in the order from one array and rank from another in typescript?

I have the following array, which has the desired order.

main_array = ['a', 'b', 'c', 'd', 'e', 'f']

From a specific process, I get another array containing only 3 elements in main_array, but it may have the elements in any order.

subset_array = ['d', 'a', 'f']

From these two arrays, I need to create an array with the ranking from the subset_array. In other words, the subset_array has the ranked items, i.e., d has rank 1, a has rank 2, and f has rank 3. Using this information, I need to build the array in the order the values appear in the main_array.

For example, from the subset_array and main_array above, I need the following array.

desired_array = [2, 0, 0, 1, 0, 3]

How can I do this in TypeScript?

>Solution :

Simplest solution due to lucky requirements

const main_array = ["a", "b", "c", "d", "e", "f"];
const subset_array = ["d", "a", "f"];

const result = main_array.map((x) => subset_array.indexOf(x) + 1);

console.log(result);

Leave a Reply