Search code examples
javascriptfunctional-programming

mapping and filtering chaining


The data looks like this

[{time: '09:00', 'level':'x3', 'type':'ae'}
time: '10:00', 'level':'x6', 'type':'fe'}
time: '09:00', 'level':'y3', 'type':'hy'}
time: '11:00', 'level':'z3', 'type':'hy'}]

The result what i would like to get: filter by the time - 09:00, and create splitted arrays for the same kinds.

Example result:

{"levels": [ "x3","y3"],"types": ["ae","hy"]}

I can do this in three function(filter and map) but I would like to chain them. Is it possible in more elegant way?

Thanks in advance.


Solution

  • Note: the result will be an object containing the two arrays. To get that object, you can use reduce like this:

    var arr = [
      {time: '09:00', 'level':'x3', 'type':'ae'},
      {time: '10:00', 'level':'x6', 'type':'fe'},
      {time: '09:00', 'level':'y3', 'type':'hy'},
      {time: '11:00', 'level':'z3', 'type':'hy'}
    ];
    
    var result = arr.filter(o => o.time === '09:00')
                    .reduce((acc, o) => {
                        acc.levels.push(o.level);
                        acc.types.push(o.type);
                        return acc;
                    }, {levels: [], types: []});
       
    console.log(result);