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);
}
}
}
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} ) ` : ''}` );
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'))
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;
}