Group and flatten data in javascript.