Skip to content

Latest commit

 

History

History
145 lines (89 loc) · 3.12 KB

File metadata and controls

145 lines (89 loc) · 3.12 KB

countIf

Count the number of elements in an array that satisfy the provided testing function.

Usage

var countIf = require( '@stdlib/array/base/count-if' );

countIf( x, predicate[, thisArg] )

Counts the number of elements in an array that satisfy the provided testing function.

var x = [ 0, 1, 0, 1, 2 ];

function predicate( val ) {
    return ( val % 2 === 0 );
}

var out = countIf( x, predicate );
// returns 3

If a predicate function returns a truthy value, the function counts that value.

The predicate function is provided three arguments:

  • value: current array element.
  • index: current array element index.
  • arr: input array.

To set the predicate function execution context, provide a thisArg.

var x = [ 1, 2, 3, 4 ];

var context = {
    'target': 3
};

function predicate( value ) {
    return ( value > this.target );
}

var out = countIf( x, predicate, context );
// returns 1

Examples

var bernoulli = require( '@stdlib/random/array/bernoulli' );
var countIf = require( '@stdlib/array/base/count-if' );

var x = bernoulli( 100, 0.5, {
    'dtype': 'generic'
});
console.log( x );

function predicate( val ) {
    return val === 1;
}
var n = countIf( x, predicate );
console.log( n );