If I have an object, like so:
const test = [
{ x: 'A', y:'1' },
{ x: 'A', y:'2' },
{ x: 'B', y:'1' },
{ x: 'A', y:'3' },
{ x: 'C', y:'1' },
];
How can I go through it, and find the in order sequence [A, B, C] from x, where [A, B, C] belongs to a unique y?
So far I tried iterating through the object using a for loop, finding all 'A', 'B', 'C', in order, but I cannot ensure that they all belong to the same y item.
Transform the array into an object of arrays corresponding to only one particular y first:
const test = [
{ x: 'A', y:'1' },
{ x: 'A', y:'2' },
{ x: 'B', y:'1' },
{ x: 'A', y:'3' },
{ x: 'C', y:'1' },
];
const reducedToYs = test.reduce((accum, { x, y }) => {
accum[y] = (accum[y] || '') + x;
return accum;
}, {});
const found = Object.entries(reducedToYs)
.find(([y, str]) => str.includes('ABC'));
console.log('y: ' + found[0] + ', entire string: ' + found[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With