How to count duplicate value in an array in javascript

前端 未结 28 1316
后悔当初
后悔当初 2020-11-22 06:07

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount =          


        
相关标签:
28条回答
  • 2020-11-22 06:29
    var counts = {};
    your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
    
    0 讨论(0)
  • 2020-11-22 06:29

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

    0 讨论(0)
  • 2020-11-22 06:30

    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]);
    } 
    
    0 讨论(0)
  • 2020-11-22 06:31

    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!

    0 讨论(0)
  • 2020-11-22 06:34

    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:
    document.write(JSON.stringify(map));
    // prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

    0 讨论(0)
  • 2020-11-22 06:34

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

    0 讨论(0)
提交回复
热议问题