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.

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;
}

Leave a Reply