183

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];

How can I count how many a,b,c are there in the array? I want to have a result like:

a = 3
b = 1
c = 2
d = 2

etc.

2

35 Answers 35

459

const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)

7
  • 15
    This is definitely the simplest answer
    – Josh Beam
    Dec 3, 2015 at 23:37
  • 7
    (counts[x] || 0)+1 how this is giving count ?
    – jsduniya
    Jan 2, 2017 at 17:30
  • 8
    @SidBhalke: The expression counts[x] || 0 returns the value of counts[x] if it is set, otherwise 0. Then just add one and set it again in the object and the count is done. Feb 7, 2017 at 11:52
  • 3
    @SheetJS if you're wondering why the downvote - it was me; I was browsing on mobile, and have clicked the button w/o actually noticing. Once I found out it was too late to revert. Apologies for that, the answer is really good. If you want to edit it, I'd be glad to reverse. Jan 19, 2019 at 10:17
  • 12
    Also with reduce: var counts = your_array.reduce((map, val) => {map[val] = (map[val] || 0)+1; return map}, {} );
    – Alberto89
    May 17, 2019 at 8:29
96

Something like this:

uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);

Use a simple for loop instead of forEach if you don't want this to break in older browsers.

3
  • 6
    @web_dev he creates an associative array object called count that will have a key value pair for each unique element in the array, where the key is the unique element value and the value is the count. He iterates over the array and for each value either increments the value or creates the key value pair (the value of the non-existent key evaluates to undefined so the || or operator takes a zero instead and adds the 1)
    – robisrob
    Jul 9, 2016 at 3:17
  • 1
    @neelmeg Maybe writing all parameters for "forEach" helps better to understand ("i" is each array value and NOT it's índex): uniqueCount.forEach(function(value, index) { count[value] = (count[value] || 0) + 1; }); Apr 4, 2017 at 23:15
  • what would be a good way to go an extra step and sort by count total?
    – tremor
    Sep 11, 2020 at 20:27
79

I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):

var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
  prev[cur] = (prev[cur] || 0) + 1;
  return prev;
}, {});

// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

EDIT:

By using the comma operator in an arrow function, we can write it in one single line of code:

var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});

// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

However, as this may be harder to read/understand, one should probably stick to the first version.

2
  • Is there a different way of doing this without the erroneous parameter reassignment? prev[cur] = (prev[cur] || 0) + 1; Sep 29, 2021 at 13:19
  • 1
    @keyboard-warrior what do you mean by "erroneous"? This is totally legal JS code. It just increments prev[cur], starting with 0. (In case, prev[0] is undefined, the value 0 is used instead). You could also use the expression (prev[cur] + 1) || 1 instead, but that doesn't make much difference.
    – isnot2bad
    Oct 9, 2021 at 11:16
36

function count() {
    array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

    array_elements.sort();

    var current = null;
    var cnt = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != current) {
            if (cnt > 0) {
                document.write(current + ' comes --> ' + cnt + ' times<br>');
            }
            current = array_elements[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        document.write(current + ' comes --> ' + cnt + ' times');
    }

}

count();

Demo Fiddle

You can use higher-order functions too to do the operation. See this answer

2
  • 1
    the extra if statement after the loop is unnecessary... just use for (var i = 0; i <= array_elements.length; i++) { or <= instead of <.
    – mmm
    Feb 9, 2015 at 1:58
  • Hi @Vinay, maybe you could help me here? stackoverflow.com/questions/57819850/…
    – SMPLYJR
    Sep 6, 2019 at 10:05
30

Simple is better, one variable, one function :)

const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

const counts = arr.reduce((acc, value) => ({
   ...acc,
   [value]: (acc[value] || 0) + 1
}), {});

console.log(counts);

3
  • I know this is old but it looks so simple. Can anyone explain what is happening here to a novice that has just learned the basic reduce usage.
    – Burton
    May 23, 2021 at 8:32
  • 1
    Sure, reduce allows you to provide a default (second argument) value and pass it back through the reduce function so you can keep checking the new value, acc (accumulative) will continually update as we're cylcing through each array value, after assigning it to the object, we can check if it exists and update it's value by 1 as we're iterating through! Hope this helps :) May 23, 2021 at 23:54
  • and change it to arr.sort().reduce(( and you have the perfect solution! 😊 (but still got my upvote) Oct 13 at 16:14
11

// Initial array
let array = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];

// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];

// This array counts duplicates [['a', 3], ['b', 2], ... , ['h', 3]] 
let duplicates = unique.map(value => [value, array.filter(str => str === value).length]);
0
11

Single line based on reduce array function

const uniqueCount =  ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] || 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));

1
10

Nobody responding seems to be using the Map() built-in for this, which tends to be my go-to combined with Array.prototype.reduce():

const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());
console.log(...result);

N.b., you'll have to polyfill Map() if wanting to use it in older browsers.

3
  • Could you explain a little bit in-depth how this is working ? (specially the set / get part). I tried to break the reducer into a function but I have "get" is not a function in response. May 7, 2020 at 7:32
  • Ok get and set functions are coming from the Map object. But the initial accumulator is not a Map object, so why does the reduced version of the reducer takes one ? May 7, 2020 at 7:39
  • @AntoineNedelec The initial value is a new Map object; see the second argument of the reduce. Map.prototype.set returns the map object, and Map.prototype.get returns undefined or the value of whatever key is supplied to it. This lets us get the current count of each letter (or 0 if undefined), then increment that by one, then set that letter's count to the new count, which returns the map and becomes the new accumulator value.
    – aendra
    May 18, 2020 at 20:13
6

I think this is the simplest way how to count occurrences with same value in array.

var a = [true, false, false, false];
a.filter(function(value){
    return value === false;
}).length                                      
1
  • The question was asking how to do this without specifying the value Sep 29, 2021 at 13:13
5

You can solve it without using any for/while loops ou forEach.

function myCounter(inputWords) {        
    return inputWords.reduce( (countWords, word) => {
        countWords[word] = ++countWords[word] || 1;
        return countWords;
    }, {});
}

Hope it helps you!

5

It is simple in javascript using array reduce method:

const arr = ['a','d','r','a','a','f','d'];
const result =  arr.reduce((json,val)=>({...json, [val]:(json[val] | 0) + 1}),{});
console.log(result)
//{ a:3,d:2,r:1,f:1 }

5
const obj = {};
const uniqueCount = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a' ];
for (let i of uniqueCount) obj[i] ? obj[i]++ : (obj[i] = 1);
console.log(obj);
4

You can have an object that contains counts. Walk over the list and increment the count for each element:

var counts = {};

uniqueCount.forEach(function(element) {
  counts[element] = (counts[element] || 0) + 1;
});

for (var element in counts) {
  console.log(element + ' = ' + counts[element]);
} 
2
  • why did you set this condition counts[element] || 0?
    – Asking
    Jun 12, 2020 at 12:06
  • The first time accessing counts[element] returns undefined since the property doesn't have a value yet. If you then try to add undefined + 1, you'll end up with NaN. The (count[element] || 0) will replace the undefined with 0 so adding 1 produces 1 instead of NaN. ECMAScript 2020 adds the nullish coalescing operator ?? which does a similar thing but is a bit more explicit that it is using the second value when the first is undefined (or null). That version would be (counts[element] ?? 0) + 1.
    – nkron
    Sep 9, 2020 at 6:18
4

// new example.
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];

function findOdd(para) {
  var count = {};
  para.forEach(function(para) {
  count[para] = (count[para] || 0) + 1;
  });
  return count;
}

console.log(findOdd(str));

3

You can do something like that:

uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();

for(var i = 0; i < uniqueCount.length; i++) {
 if(map[uniqueCount[i]] != null) {
    map[uniqueCount[i]] += 1;
} else {
    map[uniqueCount[i]] = 1;
    }
}

now you have a map with all characters count

3
uniqueCount = ["a","b","a","c","b","a","d","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach((i) => { count[i] = ++count[i]|| 1});
console.log(count);
2

Duplicates in an array containing alphabets:

var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
  sortedArr = [],
  count = 1;

sortedArr = arr.sort();

for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}

Duplicates in an array containing numbers:

var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
  sortedArr = [],
  count = 1;
sortedArr = arr.sort(function(a, b) {
  return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}

2

simplified sheet.js answare

var counts = {};
var aarr=['a','b','a'];
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );
console.log(counts)

2

CODE:

function getUniqueDataCount(objArr, propName) {
    var data = [];
    if (Array.isArray(propName)) {
        propName.forEach(prop => {
            objArr.forEach(function(d, index) {
                if (d[prop]) {
                    data.push(d[prop]);
                }
            });
        });
    } else {
        objArr.forEach(function(d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });
    }

    var uniqueList = [...new Set(data)];

    var dataSet = {};
    for (var i = 0; i < uniqueList.length; i++) {
        dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
    }

    return dataSet;
}

Snippet

var data= [
          {day:'Friday'   , name: 'John'      },
          {day:'Friday'   , name: 'John'      },
          {day:'Friday'   , name: 'Marium'    },
          {day:'Wednesday', name: 'Stephanie' },
          {day:'Monday'   , name: 'Chris'     },
          {day:'Monday'   , name: 'Marium'    },
          ];
          
console.log(getUniqueDataCount(data, ['day','name']));       
   
function getUniqueDataCount(objArr, propName) {
    var data = [];
    if (Array.isArray(propName)) {
        propName.forEach(prop => {
            objArr.forEach(function(d, index) {
                if (d[prop]) {
                    data.push(d[prop]);
                }
            });
        });
    } else {
        objArr.forEach(function(d, index) {
            if (d[propName]) {
                data.push(d[propName]);
            }
        });
    }

    var uniqueList = [...new Set(data)];

    var dataSet = {};
    for (var i = 0; i < uniqueList.length; i++) {
        dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
    }

    return dataSet;
}

2
  • How can I do it for multiple propName, say Day and Name? Feb 6, 2022 at 16:56
  • 1
    @Aqeeliqbal i have updated the code to accept an array of props now. check.
    – ARr0w
    Feb 7, 2022 at 12:51
2

Using this solution you can now get map of repeated items:

Str= ['a','b','c','d','d','e','a','h','e','a'];
var obj= new Object();

for(var i = 0; i < Str.length; i++) {
 if(obj[Str[i]] != null) {
    obj[Str[i]] += 1;
} else {
    obj[Str[i]] = 1;
    }
}
console.log(obj);

2

Steps : first check if in accumulator has the current value or not if not ,than for that particular value set the count as 1 and in else condition ,if value alreadt exist in accumulator the simple increment the count.

const testarr = [1,2,1,3,1,2,4];

var count = testarr.reduce((acc,currentval)=>{

if(acc[currentval]){ acc[currentval] = ++acc[currentval]; }else{ acc[currentval] = 1; } return acc; },{})

console.log(count);
1
var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
// here we will collect only unique items from the array
var uniqueChars = [];

// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount, 
// put it into the uniqueChars array
  if (uniqueChars.indexOf(i) == -1) {
    uniqueChars.push(i);
  } 
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item 
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
  let letterAccumulator = 0;
  for (i of uniqueCount) {
    if (i == x) {letterAccumulator++;}
  }
  console.log(`${x} = ${letterAccumulator}`);
}
1
  • Thanks for updating it, a lot more helpful to those beginning.
    – Regular Jo
    Mar 25, 2017 at 17:36
1

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);
1

Declare an object arr to hold the unique set as keys. Populate arr by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.

Given testArray:

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

solution:

var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});

JSON.stringify(arr) will output

{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}

Object.keys(arr) will return ["a","b","c","d","e","f","g","h"]

To find the occurrences of any item e.g. b arr['b'] will output 2

0
1

use forEach() method for convinience

var uniqueCount="a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count=0;
var obj={};      
uniqueCount.forEach((i,j)=>{
count=0;
var now=i;
uniqueCount.forEach((i,j)=>{
if(now==uniqueCount[j]){
count++;
obj[i]=count;
}
});
});

console.log(obj);
2
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – abdo Salm
    Oct 6, 2022 at 3:33
  • What is unclear in it? Oct 7, 2022 at 4:25
0

A combination of good answers:

var count = {};
var arr = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
var iterator = function (element) {
    count[element] = (count[element] || 0) + 1;
}

if (arr.forEach) {
    arr.forEach(function (element) {
        iterator(element);
    });
} else {
    for (var i = 0; i < arr.length; i++) {
        iterator(arr[i]);
    }
}  

Hope it's helpful.

0

By using array.map we can reduce the loop, see this on jsfiddle

function Check(){
    var arr = Array.prototype.slice.call(arguments);
    var result = [];
    for(i=0; i< arr.length; i++){
        var duplicate = 0;
        var val = arr[i];
        arr.map(function(x){
            if(val === x) duplicate++;
        })
        result.push(duplicate>= 2);
    }
    return result;
}

To Test:

var test = new Check(1,2,1,4,1);
console.log(test);
0

var string = ['a','a','b','c','c','c','c','c','a','a','a'];

function stringCompress(string){

var obj = {},str = "";
string.forEach(function(i) { 
  obj[i] = (obj[i]||0) + 1;
});

for(var key in obj){
  str += (key+obj[key]);
}
  console.log(obj);
  console.log(str);
}stringCompress(string)

/*
Always open to improvement ,please share 
*/

0

Create a file for example demo.js and run it in console with node demo.js and you will get occurrence of elements in the form of matrix.

var multipleDuplicateArr = Array(10).fill(0).map(()=>{return Math.floor(Math.random() * Math.floor(9))});
console.log(multipleDuplicateArr);

var resultArr = Array(Array('KEYS','OCCURRENCE'));

for (var i = 0; i < multipleDuplicateArr.length; i++) {
  var flag = true;
  for (var j = 0; j < resultArr.length; j++) {
     if(resultArr[j][0] == multipleDuplicateArr[i]){
       resultArr[j][1] = resultArr[j][1] + 1;
       flag = false;
      }
  }
  if(flag){
    resultArr.push(Array(multipleDuplicateArr[i],1));
  }
}

console.log(resultArr);

You will get result in console as below:

[ 1, 4, 5, 2, 6, 8, 7, 5, 0, 5 ] . // multipleDuplicateArr
[ [ 'KEYS', 'OCCURENCE' ],        // resultArr
  [ 1, 1 ],
  [ 4, 1 ],
  [ 5, 3 ],
  [ 2, 1 ],
  [ 6, 1 ],
  [ 8, 1 ],
  [ 7, 1 ],
  [ 0, 1 ] ]
0

Quickest way:

Сomputational complexity is O(n).

function howMuchIsRepeated_es5(arr) {
	const count = {};
	for (let i = 0; i < arr.length; i++) {
		const val = arr[i];
		if (val in count) {
			count[val] = count[val] + 1;
		} else {
			count[val] = 1;
		}
	}

	for (let key in count) {
		console.log("Value " + key + " is repeated " + count[key] + " times");
	}
}

howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

The shortest code:

Use ES6.

function howMuchIsRepeated_es6(arr) {
	// count is [ [valX, count], [valY, count], [valZ, count]... ];
	const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);

	for (let i = 0; i < count.length; i++) {
		console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
	}
}

howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.