Array value count javascript

How can I count the array depending on the value.. I have an array with this value..

var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";

I need to count the array depending on the value

Array with Value A is 2 Array with value B is 1

Thanks!

Answers:

Answer
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";


function count(array, value) {
  var counter = 0;
  for(var i=0;i<array.length;i++) {
    if (array[i] === value) counter++;
  }
  return counter;
}

var result = count(myArr, "a");
alert(result);

If you're interested in a built-in function... you could always add your own.

Array.prototype.count = function(value) {
  var counter = 0;
  for(var i=0;i<this.length;i++) {
    if (this[i] === value) counter++;
  }
  return counter;
};

Then you could use it like this.

var result = myArr.count("a");
alert(result);
Answer

Oh well, beaten to the punch, but here's my version.

var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b"

getCountFromVal( 'a', myArr );

function getCountFromVal( val, arr )
{
    var total =  arr.length;
    var matches = 0;

    for( var i = 0; i < total; i++ )
    {
        if( arr[i] === val )
        {
            matches++;
        }
    }

    console.log(matches);
    return matches;
}
Answer

Live Demo: http://jsfiddle.net/CLjyj/1/

var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";

function getNum(aVal)
{
    num=0;
    for(i=0;i<myArr.length;i++)
    {
        if(myArr[i]==aVal)
            num++;
    }
    return num;
}

alert(getNum('a')); //here is the use
Answer

I would use Array.filter

  var arr = ['a', 'b', 'b']
  arr.filter(val => val === 'b').length // 2
Answer

Everyone's already given the obvious function, so I'm going to try and make another solution:

var myArr = [];
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";

function count(arr, value){
    var tempArr = arr.join('').split(''), //Creates a copy instead of a reference
        matches = 0,
        foundIndex = tempArr.indexOf(value); //Find the index of the value's first occurence
    while(foundIndex !== -1){
        tempArr.splice(foundIndex, 1); //Remove that value so you can find the next
        foundIndex = tempArr.indexOf(value);
        matches++;
    }
    return matches;
}

//Call it this way
document.write(count(myArr, 'b'));

Demo

Answer

You can use Lodash's countBy function:

_.countBy(myArr);

Example:

var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";

const result = _.countBy(myArr);

// Get the count of `a` value
console.log('a', result.a);

// Get the count of `b` value
console.log('b', result.b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

countBy Documentation

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.