admin管理员组

文章数量:1129122

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.

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.

Share Improve this question edited Jan 5, 2016 at 15:43 ROMANIA_engineer 56.5k30 gold badges208 silver badges205 bronze badges asked Oct 16, 2013 at 4:28 detno29detno29 2,2316 gold badges20 silver badges21 bronze badges 2
  • 1 possible duplicate of stackoverflow.com/questions/12749200/… – Vinay Pratap Singh Bhadauria Commented Oct 16, 2013 at 4:30
  • @Nirk I presume that musical_coder meant a map as in {}, not functional programming's map. – Matt Ball Commented Oct 16, 2013 at 13:35
Add a comment  | 

37 Answers 37

Reset to default 1 2 Next 467

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

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.

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.

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

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);


// 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]);

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.

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));

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                                      

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]);
} 

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!

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 }

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);

// 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));

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

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);

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);

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>");
}

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

simplified sheet.js answare

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

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;
}

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);

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}`);
}

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 ] ]

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);

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);

Just in case somebody want to count duplicate objects inside an array, this is how to do it

const array = [
    { x: 1, y: 2 },
    { x: 3, y: 4 },
    { x: 1, y: 2 },
    { x: 3, y: 4 },
    { x: 1, y: 2 },
    { x: 3, y: 12 },
]

const result = [
    ...array
        .reduce((r, e) => {
            let k = `${e.x}|${e.y}`
            if (!r.has(k)) r.set(k, { ...e, count: 1 })
            else r.get(k).count++
            return r
        }, new Map())
        .values(),
]

console.log(result)
// out put
[
  { x: 1, y: 2, count: 3 },
  { x: 3, y: 4, count: 2 },
  { x: 3, y: 12, count: 1 }
]

replace x and y with the property you want to check in your array.

I found another solution for this question is simplest and shorter than others responses for example :

const users = ["john", "roze", "mat", "anastasia", "tom", "john", "mat", "alex", "john", "anastasia", "mat", "john"];

const result = users.reduce((obj, currentUser) => {
  obj[currentUser] = obj[currentUser] ? obj[currentUser] + 1 : 1;

  return obj;
}, {});

console.log(result);

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.

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 
*/

本文标签: How to count duplicate value in an array in javascriptStack Overflow