Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find consecutive object properties in array of objects

I have an array of objects and I need to find out if this array contains n-consecutive appearances of an object property without having any other value in between.

Lets say the object array looks like this

[{side:"buy"}, {side:"sell"}, {side:"sell"}, {side:"buy"}]

What I want is to check if the array has for example 3 consecutive "buy" properties without any "sell" inbetween and vice versa.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any easier or cleaner way than using a for loop and checking i+1, i+2 on every iteration?

Approach I got now

function getConsecutiveTradesByTradeSide(trades, tradeSide, validator) {
  let counter = 0;
  for (let i = 0; i < trades.length; i++) {
    const temp = trades[i];
    if (temp.attributes.side == tradeSide) {
      counter++;
      if (counter === validator) return trades.slice(i - validator, i);
    }
  }
}

>Solution :

Because there’s lots of fun/wild answers I’ll share mine.

I’m taking this:

"What I want is to check if the array has for example 3 consecutive "buy" properties without any "sell" inbetween and vice versa."

As meaning that the function should return true if there’s 3 consecutive buy/sell properties.

I’m using a simple function, because it’s often a lot more legible than a .reduce function, as demonstrated by the other answers.

function checkConsecutiveTrades(trades, side = 'buy', threshold = 3) {

  let counter = 0;
  for(const trade of trades) {
    if (trade.side === side) {
      counter++;
    } else { 
      counter = 0;
    }
    if (counter===threshold) return true;
  }

  return false;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading