-1

I want to check an array, if it contains a value n times successively.

Example:
var array = [true, true, true, true, false]; ==> true, if true 4 times successively

var array = [true, false, false, true, true]; ==> false

Fritzl
  • 43
  • 7

5 Answers5

0

You need a counter and a quantifier, like Array#some. Then check the value and increment on true or reset counter to zero.

function check4(array) {
    var count = 0;
    return array.some(function (a) {
        return a ? ++count === 4 : count = 0;
    });
}

console.log(check4([true, true, true, true, false]));  // true
console.log(check4([true, true, true, false, true]));  // false
console.log(check4([true, false, false, true, true])); // false
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This can be achieved with reduce:

const spree = array.reduce((acum, el) => el === val ? acum + 1 : 0, 0);
if (spree > 4) ...
lilezek
  • 6,976
  • 1
  • 27
  • 45
0

You can do something like this - this function accepts an array, the number of times you're checking for, and the value you're testing.

     function check (arr, number,val) {
  result=false;
    counter=1;
    for (i=1; i<arr.length; i++) {
        if (arr[i]===arr[i-1]) {counter++;} else {counter=1;}
        console.log(counter);
        if (counter>=number) {result=true;}
    }
    return result;
};

Of course, there are more elegant ways (you can break the moment you find a false), and the counters can be handled more elegantly.

NadavM
  • 35
  • 7
0

The shortest one:

var has4True = function(arr){ 
    return /(true){4}/.test(arr.join('')); 
};

console.log(has4True([false, true, true, true, true, false]));
console.log(has4True([true, false, false, true, true]));
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0
var testArray = [true, true, true, true, false];
var searchVal = true;
var findTarget = 4;
var findAmount = 0;

for (var i=0; i<testArray.length; i++)
{
    if (testArray[i] == searchVal)
    {
        findAmount++;
    }
}

var findSuccess = (findAmount == findTarget);

testArray can contain any value to test against.

searchVal is the value to test against.

findTarget is how many times it needs to be found.

findSuccess will contain a true or false based on whether the condition has been met.