javascript Javascript:计算数组中的重复项

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Javascript:计算数组中的重复项相关的知识,希望对你有一定的参考价值。

/** 
Problem:

You have a javascript array that likely has some duplicate values and you would like a count of those values.
Solution:

Try this schnippet out.
*/


function compressArray(original) {
 
	var compressed = [];
	// make a copy of the input array
	var copy = original.slice(0);
 
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
 
		var myCount = 0;	
		// loop over every element in the copy and see if it's the same
		for (var w = 0; w < copy.length; w++) {
			if (original[i] == copy[w]) {
				// increase amount of times duplicate is found
				myCount++;
				// sets item to undefined
				delete copy[w];
			}
		}
 
		if (myCount > 0) {
			var a = new Object();
			a.value = original[i];
			a.count = myCount;
			compressed.push(a);
		}
	}
 
	return compressed;
};

// It should go something like this:

var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat");
var newArray = compressArray(testArray);
 
/*
console: [
	Object { value="dog", count=2}, 
	Object { value="cat", count=3}, 
	Object { value="buffalo", count=1}, 
	Object { value="wolf", count=1}, 
	Object { value="tiger", count=1}
]
*/

以上是关于javascript Javascript:计算数组中的重复项的主要内容,如果未能解决你的问题,请参考以下文章

使用JavaScript计算字符串中的句子数

解决JavaScript浮点数计算精度问题

JavaScript倒计时算法(计算剩余多少天)实现

javascript计算两个时间差

自己动手丰衣足食-JavaScript-输入数字,计算出从1到这个数的阶乘和

javascript获取某个时间的毫秒数