I have an array of objects and I need to convert it into an array of arrays grouped together based on position, but maintaining the order of the items.
This is what I did:
const data = [{
position: 'left',
message: 'a'
}, {
position: 'left',
message: 'b'
}, {
position: 'left',
message: 'c'
}, {
position: 'right',
message: 'd'
}, {
position: 'right',
message: 'e'
}, {
position: 'left',
message: 'f'
}, {
position: 'left',
message: 'g'
}]
console.log(data.reduce((a, c) => {
let b = [];
let d = [];
if (c.position === 'left') {
b.push(c.message)
}
if (c.position === 'right') {
d.push(c.message)
}
a.push(b)
return a
}, []))
Expected output:
[['a', 'b', 'c'], ['d', 'e'], ['f', 'g']]
The same position elements are grouped together in an array and if the next position is different, it is grouped together in a different array and goes on. For example, 'a' 'b' 'c' are position left and they are grouped inside an array, 'd' 'e' are positioned right, they are grouped together as the second array and 'f' 'g' are left positioned, they are grouped as 3rd array.
Thanks.
reduceis a perfectly valid solution to this problem.