计算数组中的重复项

编程入门 行业动态 更新时间:2024-10-20 20:36:43
本文介绍了计算数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

计算数组中的重复项

本文发布于:2023-11-22 13:49:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!