本文介绍了计算数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试显示我的数组的内容,但是存在重复项的地方只需打印名称和数字,例如
I'm trying to display the contents of my array but where duplicates exist just print the name and the number e.g
myArr = ['apple', 'apple', 'orange', 'apple', 'banana', 'orange', 'pineapple']会显示;
apple 3 orange 2 banana pineapple到目前为止,我将它们全部作为字符串返回:
So far I'm returning them all as a string:
arrList = myArr.join(', '); arrList.toString()推荐答案
漫长的路
var elements = ["apple", "apple", "orange", "apple", "banana"]; elements.sort(); var current = null; var count = 0; for(var i = 0; i < elements.length; i++) { if(elements[i] != current) { if(count > 0) { document.write(current + " " + count + "<br/>"); } current = elements[i]; count = 1; } else { count++; } } if(count > 0) { document.write(current + " " + count);短路
var elements = ["apple", "apple", "orange", "apple", "banana"]; var counts = {}; elements.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); document.write("Apple: " + counts.apple + "<br/>"); document.write("Banana: " + counts.banana + "<br/>"); document.write("Orange: " + counts.orange + "<br/>");更多推荐
计算数组中的重复项
发布评论