3

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.

1
  • 1
    Remember add = after const test Commented May 2, 2018 at 0:30

2 Answers 2

3

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]);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is great. I should learn how to use these properly. Just curious, was this something that was possible with a for loop? Thank you.
Sure, you can do anything with a for loop - which is exactly the problem with for loops IMO. Using the array methods instead offers better abstraction, does not require manual iteration, and gives a clearer picture of what the function is doing.
0

Create a function that takes the target Y value. Loop through the test array and compare the y value to your target value and if it matches - push the x value into an array. Then return that array.

If a string is required ("ABC)" then rather than creating an array create a string and append the x value to it to build the string that is then returned.

const test = [
  { x: 'A', y:'1' },
  { x: 'A', y:'2' },
  { x: 'B', y:'1' },
  { x: 'A', y:'3' },
  { x: 'C', y:'1' },
];



function testValue(str) {
    let xArray = [];
    test.forEach(function(item) { 
      if(item['y'] === str) {xArray.push(item['x'])}
   })
  return xArray;
  }
  
console.log(testValue('1')) // gives ["A", "B", "C"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.