How to count duplicate value in an array in javascript

前端 未结 28 2104
后悔当初
后悔当初 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: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']);

提交回复
热议问题