Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading