How to flatten structure with Seq module

I want to flatten the following sequence structure of:

let questions = [
     { question: 1, answers: ["A", "F", "C"] },
     { question: 2, answers: ["A", "B"] }
];

to:

let questions = [
     { question: 1, answers: "A" },
{ question: 1, answers: "F" },
{ question: 1, answers: "C" },
{ question: 2, answers: "A" },
{ question: 2, answers: "B" }}
];

How would I go about this using the Seq module?

Hello,

For this, you would typically use the collect function together with the map function. This “fanning-out” move is pretty common.

The idea is: for each question, return one item per answer, and make that item be a combination of question and answer. The collect function represents the one-to-many mapping, the map function represents the one-to-one mapping.

Here’s a simple program which does what you ask:

open Seq;

let questions = [
     { question: 1, answers: ["A", "F", "C"] },
     { question: 2, answers: ["A", "B"] }
];

return questions.collect(q =>
   q.answers.map(a => { question: q.question, answer: a})
);
1 Like