0

Sorry for bad title, I don't really know how to phrase this and this might be trivial problem ...

The data that comes from the array looks like this, each name can have an indefinite amount of sequence, what I want to do is group them by name and put each sequence in an array

[
{
    name: 'Mike',
    sequence: 'AAAA',
},
{
    name: 'Bob',
    sequence: 'ABAB',
},
{
    name: 'Bob',
    sequence: 'AAAB',
},
{
    name: 'Marvin',
    sequence: 'AAAA',
},
{
    name: 'Marvin',
    sequence: 'AABA',
},
{
    name: 'Marvin',
    sequence: 'BBBB',
},
]

What I am looking to return for each name by using console.log(name, array) for example would be something like this

Mike ["AAAA"]
Bob ["ABAB","AAAB"]
Marvin ["AAAA","AABA","BBBB"]

Thank you very much!

cmw
  • 23
  • 5

2 Answers2

1

As mentioned in the comments, it seems you have tried some ways to solve the problem.

You can try following solution

  • Use Array.reduce to convert your array into an object with keys as name and value as array of sequences
  • In the reduce function, check whether the name exist in the resultant object. If it exists, concat the sequence to it (using spread syntax) else add a new entry with an array with sequence.

let input = [{name:'Mike',sequence:'AAAA',},{name:'Bob',sequence:'ABAB',},{name:'Bob',sequence:'AAAB',},{name:'Marvin',sequence:'AAAA',},{name:'Marvin',sequence:'AABA',},{name:'Marvin',sequence:'BBBB',}];
let result = input.reduce((a, {name, sequence}) => Object.assign(a, {[name] : a[name] ? [...a[name], sequence]: [sequence]}), {});
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • 1
    Excellent! I did not know about reduce, I do not understand the function yet but I know what to use it with next. – cmw Jun 03 '21 at 16:40
-1
inputArray.reduce((acc,{name,sequence}) => { 
                       let obj = acc.find(a => a.name === name); 
                       obj ? obj.sequence.push(sequence) 
                           : acc.push({name,sequence:[sequence]}); 
                       return acc;
                    }, [])
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18