Reputation: 7141
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.
Upvotes: 2
Views: 1566
Reputation: 23
this is an old question, but I always advocate for ONLY using reduce
when more than one array method is being chained together
const tmp = [
{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'}
]
const result = tmp.reduce((acc, { time, level, type }) => {
if (time === '09:00') {
acc.levels.push(level)
acc.types.push(type)
}
return acc
}, { levels: [], types: [] })
this cuts down on iterations and gives the same result
Upvotes: 0
Reputation: 1763
var tmp = [{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 = {}; result.levels = []; result.types = [];
tmp.filter(data => data.time === '09:00').map(data => {
result.levels.push(data.level);
result.types.push(data.type);
});
console.log(result);
Upvotes: 0
Reputation: 386560
Just filter and map the properties you want and get an object with wanted properties and all values in an array.
var array = [{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'}],
result = array.
filter(a => a.time === '09:00').
map(({ level, type }) => ({ level, type })).
reduce((r, o, i) => (Object.keys(o).forEach(k => (r[k] = r[k] || []).push(o[k])), r), {});
console.log(result);
Upvotes: 0
Reputation: 31682
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);
Upvotes: 2