Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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);
    }
  }
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

One option is to use the array method some. The following code keeps track of the number of consecutive buy and sellevents in the variables n_buy and n_sell, respectively. If the length of any runs exceeds the threshold, the search is aborted.

let a_t = [{side:"buy"}, {side:"sell"}, {side:"sell"}, {side:"sell"}, {side:"buy"}]
  , b_result
  , n_buy
  , n_sell
  , n_threshold = 3
  , s_runOf = null
  ;

n_buy  = 0;
n_sell = 0;
b_result = a_t.some ( po_event => {
    let b_found = false;
    
    if (po_event.side === "sell") {
        n_sell++;
        n_buy = 0;
        b_found = (n_sell >= n_threshold);
        if (b_found) { s_runOf = "sell"; }
    }
    if (po_event.side === "buy") {
        n_buy++;
        n_sell = 0;
        b_found = (n_buy >= n_threshold);
        if (b_found) { s_runOf = "buy"; }
    }
    
    return b_found;
});

console.log ( `${n_threshold} identical consecutive signals: ${b_result}.${b_result ? ` ( ${s_runOf} ) ` : ''}` );

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do something like this

const data = [{side:"buy"}, {side:"sell"}, {side:"sell"}, {side:"buy"}]
const data2 = [{side:"buy"}, {side:"buy"}, {side:"buy"}, {side:"buy"}, {side: "sell"}]

const calculateBuyInRow = (data, value) => data.reduce((res, {side}) => side === value?{current: res.current + 1, maxOccurencies: Math.max(res.maxOccurencies, res.current + 1)}: {...res, current: 0} , {current: 0, maxOccurencies: 0}).maxOccurencies > 3



console.log(calculateBuyInRow(data, 'buy'))
console.log(calculateBuyInRow(data2, 'buy'))

about 4 years ago · Juan Pablo Isaza Relatório

0

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;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda