title: Flatten and sort nested array of object by its array value
body: <pre><code>// My data is like this
  const data = [
    { 
      id: 1,
      color: &quot;red&quot;,
      time: [ 
       { start: new Date(&quot;2021-4-3&quot;), end: new Date(&quot;2021-4-4&quot;) }, 
       { start: new Date(&quot;2021-4-2&quot;), end: new Date(&quot;2021-4-3&quot;) }
      ]
    },
    {
      id: 2,
      color: &quot;blue&quot;,
      time: [ 
       { start: new Date(&quot;2021-4-2&quot;), end: new Date(&quot;2021-4-3&quot;) }
      ]
    }
  ]
  
  </code></pre>
  <p>And I want to sort time then adjust the data like below.</p>
  <pre><code>[
    { id: &quot;1-0&quot;, start: new Date(&quot;2021-4-2&quot;), end: new Date(&quot;2021-4-3&quot;), color: &quot;red&quot; },
    { id: &quot;1-1&quot;, start: new Date(&quot;2021-4-3&quot;), end: new Date(&quot;2021-4-4&quot;), color: &quot;red&quot; },
    { id: &quot;2-0&quot;, start: new Date(&quot;2021-4-2&quot;), end: new Date(&quot;2021-4-3&quot;), color: &quot;blue&quot; },
  ]
  </code></pre>
  <p>I want to know is there have <strong>better algorithm</strong> to handle this situation? Below is my attempt.
  (I also attempted ES6 syntax <code>reduce</code>, <code>flatMap</code> and <code>flat</code>, but I can't find the better way to handle this situation.)</p>
  <pre><code>let arr = [];
  let timeLength = 0;
  for (let i = 0; i &lt; data.length; i++) {
    timeLength = data[i].time.length;
    if (timeLength !== 1) {
      data[i].time.sort((a, b) =&gt; new Date(a.start) - new Date(b.start)); // sort time
    }
    for (let j = 0; j &lt; timeLength; j++) {
      arr.push({
        id: data[i].id + &quot;-&quot; + i,
        color: data[i].color,
        start: data[i].time[j].start,
        end: data[i].time[j].end,
      });
    }
  }
  </code></pre>