My task involves taking an array of objects and converting it into nested arrays based on the position property, while still preserving the original order.
Here is my approach:
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
}, []))
Desired output:
[['a', 'b', 'c'], ['d', 'e'], ['f', 'g']]
The elements with the same position are grouped together in their own array. If the position changes, a new array is created for the next set of elements. For example, 'a' 'b' 'c' have left position and form one array, 'd' 'e' have right position and are in another array, and 'f' 'g' also have left position forming a separate array.
Thank you.