计算数组中的唯一元素而不进行排序 [英] Count unique elements in array without sorting

查看:101
本文介绍了计算数组中的唯一元素而不进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,以下内容将查找数组中的元素数。假设数组中至少有一个元素

In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array

arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
    if (arr[i] == arr[i+1])
    {
      count +=1;
    }
    else
    {
        results += arr[i] + " --> " + count + " times\n" ;
        count=1;
    }
}

是否可以在不使用sort()的情况下执行此操作或者不以任何方式改变数组?我想可能必须重新创建数组,然后可以在新创建的数组上完成排序,但我想知道没有排序的最佳方法是什么。
是的,我是艺术家,而不是程序员,是你的荣誉。

Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting. And yes, I'm an artist, not a programmer, your honour.

推荐答案

快速执行此操作的方法是将唯一元素复制到对象中。

A quick way to do this is to copy the unique elements into an Object.

var counts = {};
for (var i = 0; i < arr.length; i++) {
    counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}

当此循环完成时,计算 object将拥有数组中每个不同元素的计数。

When this loop is complete the counts object will have the count of each distinct element of the array.

这篇关于计算数组中的唯一元素而不进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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