Design & Download
Your JS Library
in Seconds!!!

Snippet: count()

Written by Christopher West (cwest) on July 13, 2016.
Count the items in an array or an object or count the characters in a string.
function count(subject, opt_fnFilter) {
  opt_fnFilter = getSimpleCallback(opt_fnFilter);
  var count = 0, noFilter = arguments.length < 2, isStr = typeOf(subject, 'String');
  if (noFilter && isStr) {
    return subject.length;
  }
  walk(isStr ? subject.split('') : subject, function() {
    count += noFilter || !!opt_fnFilter.apply(this, arguments);
  });
  return count;
}

count(...) API Documentation

Count the items in an array or an object or count the characters in a string.

Parameters

  1. subject {Array|Object|string}:
    The array, object or string to count parts of.
  2. opt_fnFilter {Function}:
    Optional. If specified, this function will be called for each item (or character in the case that subject is a string) of subject. This function will be passed the following arguments:
    1. value {*}:
      In the case that subject is an array or an object this will be an individual value defined. In the case that subject is a string this will be a single character.
    2. key {number|string}:
      In the case that subject is an array or a string this will be the index of the value. In the case that subject is an object this will be key of the value.
    3. subject {Array|Object|string}:
      The subject passed into count().
    The return value of this function will be evaluated to determine whether or not to count the item in question. A true-ish value will cause the item to be counted.

Returns

The number of items counted. If no opt_fnFilter is given all items in subject will be counted.

Example

console.log(count(new Array(36)));  // -> 0
console.log(count({fName:'Chris',lName:'West'}));  // -> 2
console.log(count('hello'));  // -> 5
console.log(count([3,'sd',null,undefined]));  // -> 4