# 计算数组元素的出现次数/频率

2020/10/13 12:21 · javascript ·  · 0评论

``````5, 5, 5, 2, 2, 2, 2, 2, 9, 4
``````

``````5, 2, 9, 4
``````

``````3, 5, 1, 1
``````

### 注意

``````var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

function foo(arr) {
var a = [],
b = [],
prev;

arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length - 1]++;
}
prev = arr[i];
}

return [a, b];
}

var result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')``````

``````var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counts = {};

for (var i = 0; i < arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}

console.log(counts[5], counts[2], counts[9], counts[4]);``````

``````console.log(counts[5]); // logs '3'
``````

``````keys(counts); // returns ["5", "2", "9", "4"]
``````
``````var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}

return acc;
}, {});

// a == {2: 5, 4: 1, 5: 3, 9: 1}
``````

``````_.countBy(array);
``````

``````_.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
=> Object {2: 5, 4: 1, 5: 3, 9: 1}
``````

``````a      = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
result = { };
for(var i = 0; i < a.length; ++i) {
if(!result[a[i]])
result[a[i]] = 0;
++result[a[i]];
}
``````

``````{
2: 5,
4: 1,
5: 3,
9: 1
}
``````

ECMAScript2015选项如何。

``````const a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

const aCount = new Map([...new Set(a)].map(
x => [x, a.filter(y => y === x).length]
));
``````
``````aCount.get(5)  // 3
aCount.get(2)  // 5
aCount.get(9)  // 1
aCount.get(4)  // 1
``````

``````Array [
[5, 3],
[2, 5],
[9, 1],
[4, 1]
]
``````

``````Map {
5 => 3,
2 => 5,
9 => 1,
4 => 1
}
``````

``````var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
``````

``````const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
``````

``````var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]

const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());

console.info([...map.keys()])
console.info([...map.values()])
console.info([...map.entries()])``````
``````const data = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]

function count(arr) {
return arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {})
}

console.log(count(data))``````

`arr.reduce(function(countMap, word) {countMap[word] = ++countMap[word] || 1;return countMap}, {});`

ES6版本应该简化很多（另一行解决方案）

``````let arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
let acc = arr.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());

console.log(acc);
// output: Map { 5 => 3, 2 => 5, 9 => 1, 4 => 1 }
``````

• 2017 edit：我`||`用来减少代码大小并使它更具可读性。
``````var a=[7,1,7,2,2,7,3,3,3,7,,7,7,7];

a.reduce((r,k)=>{r[k]=1+r[k]||1;return r},{})

));``````

``````var s="ABRACADABRA";

s.split('').reduce((a, c)=>{a[c]++?0:a[c]=1;return a},{})

));``````

``````a = ['foo', 'foo', 'bar'];

var results = _.reduce(a,function(counts,key){ counts[key]++; return counts },
_.object( _.map( _.uniq(a), function(key) { return [key, 0] })))
``````

``````_.keys(results)
``````

``````_.values(results)
``````

``````function count(a,i){
var result = 0;
for(var o in a)
if(a[o] == i)
result++;
return result;
}
``````

``````function count(a){
var result = {};
for(var i in a){
if(result[a[i]] == undefined) result[a[i]] = 0;
result[a[i]]++;
}
return result;
}
``````

``````const arr = [2, 2, 2, 3, 2]

const count = arr.reduce((pre, cur) => (cur === 2) ? ++pre : pre, 0)
console.log(count) // 4``````

``````let countMap = array.reduce(
(map, value) => {map.set(value, (map.get(value) || 0) + 1); return map},
new Map()
)
``````

``````let countObject = array.reduce(
(map, value) => { map[value] = (map[value] || 0) + 1; return map },
{}
)
``````

``````let countObject = array.reduce(
(value, {[value]: count = 0, ...rest}) => ({ [value]: count + 1, ...rest }),
{}
)
``````

``````countMap.forEach((count, value) => console.log(`value: \${value}, count: \${count}`)

let values = countMap.keys()
let counts = countMap.values()
``````

``````Object
.entries(countObject) // convert to array of [key, valueAtKey] pairs
.forEach(([value, count]) => console.log(`value: \${value}, count: \${count}`)

let values = Object.keys(countObject)
let counts = Object.values(countObject)
``````

``````{
// create array with some pseudo random values (1 - 5)
const arr = Array.from({length: 100})
.map( () => Math.floor(1 + Math.random() * 5) );
// frequencies using a reducer
const arrFrequencies = arr.reduce((acc, value) =>
({ ...acc, [value]: acc[value] + 1 || 1}), {} )
console.log(`Value 4 occurs \${arrFrequencies[4]} times in arrFrequencies`);

// bonus: restore Array from frequencies
const arrRestored = Object.entries(arrFrequencies)
.reduce( (acc, [key, value]) => acc.concat(Array(value).fill(+key)), [] );
console.log(arrRestored.join());
}``````
``.as-console-wrapper { top: 0; max-height: 100% !important; }``

``````var array = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

function countDuplicates(obj, num){
obj[num] = (++obj[num] || 1);
return obj;
}

// answer => {2:5, 4:1, 5:3, 9:1};
``````

``````var uniqueNums = Object.keys(answer);
// uniqueNums => ["2", "4", "5", "9"];

// countOfNums => [5, 1, 3, 1];
``````

``````var uniqueNums = Object.keys(answer).map(key => +key);
// uniqueNums => [2, 4, 5, 9];
``````

``````var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

const countOccurrences = (arr) => {
const map = {};
for ( var i = 0; i < arr.length; i++ ) {
map[arr[i]] = ~~map[arr[i]] + 1;
}
return map;
}
``````

``````const testArray = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]

const counfFrequency = R.compose(
R.map(R.length),
R.groupBy(R.identity),
)

counfFrequency(testArray)
``````

``````const dataset = [2,2,4,2,6,4,7,8,5,6,7,10,10,10,15];
let values = [];
let keys = [];

var mapWithOccurences = dataset.reduce((a,c) => {
if(a.has(c)) a.set(c,a.get(c)+1);
else a.set(c,1);
return a;
}, new Map())
.forEach((value, key, map) => {
keys.push(key);
values.push(value);
});

console.log(keys)
console.log(values)``````

```const ary = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]; R.countBy(r=> r)(ary) ```
countBy文档在

``````const values = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequency = _.map(_.groupBy(values), val => ({ value: val[0], frequency: val.length }));
console.log(frequency);``````
``<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>``

``````// The initial array we want to count occurences
var initial = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

// The count array asked for
var count = Array.from(new Set(initial)).map(val => initial.filter(v => v === val).length);

// Outputs [ 3, 5, 1, 1 ]
``````

``````var set = Array.from(new Set(initial));

//set = [5, 2, 9, 4]
``````

``````<html>
<script>
// array with values
var ar = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

var Unique = []; // we'll store a list of unique values in here
var Counts = []; // we'll store the number of occurances in here

for(var i in ar)
{
var Index = ar[i];
Unique[Index] = ar[i];
if(typeof(Counts[Index])=='undefined')
Counts[Index]=1;
else
Counts[Index]++;
}

// remove empty items
Unique = Unique.filter(function(){ return true});
Counts = Counts.filter(function(){ return true});

var a=[];

for(var i=0; i<Unique.length; i++)
{
a.push(Unique[i] + ':' + Counts[i] + 'x');
}

</script>
<body>

</body>
</html>
``````

``````Array.prototype.getItemCount = function(item) {
var counts = {};
for(var i = 0; i< this.length; i++) {
var num = this[i];
counts[num] = counts[num] ? counts[num]+1 : 1;
}
return counts[item] || 0;
}
``````

``````function mostFrequentItemCount(collection) {
collection.sort(function(a, b){return a-b});
var i=0;
var ans=[];
var int_ans=[];
while(i<collection.length)
{
if(collection[i]===collection[i+1])
{
int_ans.push(collection[i]);
}
else
{
int_ans.push(collection[i]);
ans.push(int_ans);
int_ans=[];
}
i++;
}

var high_count=0;
var high_ans;

i=0;
while(i<ans.length)
{
if(ans[i].length>high_count)
{
high_count=ans[i].length;
high_ans=ans[i][0];
}
i++;
}
return high_ans;
}
``````

``````var big_array = [
{ name: "Pineapples", quantity: 3 },
{ name: "Pineapples", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Limes", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Pineapples", quantity: 2 },
{ name: "Pineapples", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Bananas", quantity: 5 },
{ name: "Coconuts", quantity: 1 },
{ name: "Lemons", quantity: 2 },
{ name: "Oranges", quantity: 1 },
{ name: "Lemons", quantity: 1 },
{ name: "Limes", quantity: 1 },
{ name: "Grapefruit", quantity: 1 },
{ name: "Coconuts", quantity: 5 },
{ name: "Oranges", quantity: 6 }
];

function countThem() {
var names_array = [];
for (var i = 0; i < big_array.length; i++) {
names_array.push( Object.assign({}, big_array[i]) );
}

function outerHolder(item_array) {
if (item_array.length > 0) {
var occurrences = [];
var counter = 0;
var bgarlen = item_array.length;
item_array.sort(function(a, b) { return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0); });

function recursiveCounter() {
occurrences.push(item_array[0]);
item_array.splice(0, 1);
var last_occurrence_element = occurrences.length - 1;
var last_occurrence_entry = occurrences[last_occurrence_element].name;
var occur_counter = 0;
var quantity_counter = 0;
for (var i = 0; i < occurrences.length; i++) {
if (occurrences[i].name === last_occurrence_entry) {
occur_counter = occur_counter + 1;
if (occur_counter === 1) {
quantity_counter = occurrences[i].quantity;
} else {
quantity_counter = quantity_counter + occurrences[i].quantity;
}
}
}

if (occur_counter > 1) {
var current_match = occurrences.length - 2;
occurrences[current_match].quantity = quantity_counter;
occurrences.splice(last_occurrence_element, 1);
}

counter = counter + 1;

if (counter < bgarlen) {
recursiveCounter();
}
}

recursiveCounter();

return occurrences;
}
}
}
``````
``````function countOcurrences(arr){
return arr.reduce((aggregator, value, index, array) => {
if(!aggregator[value]){
return aggregator = {...aggregator, [value]: 1};
}else{
return aggregator = {...aggregator, [value]:++aggregator[value]};
}
}, {})
}
``````

``````Array.prototype.count = function(obj){
var count = this.length;
if(typeof(obj) !== "undefined"){
var array = this.slice(0), count = 0; // clone array and reset count
for(i = 0; i < array.length; i++){
if(array[i] == obj){ count++ }
}
}
return count;
}
``````

``````let array = ['a', 'b', 'd', 'a', 'c'];
array.count('a'); // => 2
array.count('b'); // => 1
array.count('e'); // => 0
array.count(); // => 5
``````

### 编辑

``````let occurred = [];
array.filter(function(item) {
if (!occurred.includes(item)) {
occurred.push(item);
return true;
}
}); // => ["a", "b", "d", "c"]
``````

``````occurred.map(array.count.bind(array)); // => [2, 1, 1, 1]
``````

``````let occurrences = {}
occurred.forEach(function(item) { occurrences[item] = array.count(item) });
occurences; // => {2: 5, 4: 1, 5: 3, 9: 1}
``````