Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Through An Object In JavaScript

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.

like image 727
BlueishVelvet Avatar asked Dec 19 '25 09:12

BlueishVelvet


1 Answers

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]);
like image 152
CertainPerformance Avatar answered Dec 21 '25 22:12

CertainPerformance