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!
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!
Share Improve this question asked Dec 22, 2011 at 17:12 user1033600user1033600 2894 gold badges8 silver badges17 bronze badges 06 Answers
Reset to default 5var 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);
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;
}
Live Demo: http://jsfiddle/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
I would use Array.filter
var arr = ['a', 'b', 'b']
arr.filter(val => val === 'b').length // 2
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
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./ajax/libs/lodash.js/4.17.15/lodash.js"></script>
countBy
Documentation