计算数组中的重复项 [英] Count duplicates in an array

查看:90
本文介绍了计算数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示我的数组的内容,但是存在重复项的地方只需打印名称和数字,例如

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

这篇关于计算数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆