计算数组元素的出现次数/频率 [英] Counting the occurrences / frequency of array elements

查看:28
本文介绍了计算数组元素的出现次数/频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Javascript 中,我试图获取一个初始数值数组并计算其中的元素.理想情况下,结果将是两个新数组,第一个指定每个唯一元素,第二个包含每个元素出现的次数.但是,我愿意接受有关输出格式的建议.

In Javascript, I'm trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each unique element, and the second containing the number of times each element occurs. However, I'm open to suggestions on the format of the output.

例如,如果初始数组是:

For example, if the initial array was:

5, 5, 5, 2, 2, 2, 2, 2, 9, 4

然后将创建两个新数组.第一个将包含每个唯一元素的名称:

Then two new arrays would be created. The first would contain the name of each unique element:

5, 2, 9, 4

第二个将包含该元素在初始数组中出现的次数:

The second would contain the number of times that element occurred in the initial array:

3, 5, 1, 1

因为数字 5 在初始数组中出现了 3 次,所以数字 2 出现了 5 次,而 9 和 4 都出现了一次.

Because the number 5 occurs three times in the initial array, the number 2 occurs five times and 9 and 4 both appear once.

我已经搜索了很多解决方案,但似乎没有任何效果,而且我自己尝试过的一切都变得异常复杂.任何帮助将不胜感激!

I've searched a lot for a solution, but nothing seems to work, and everything I've tried myself has wound up being ridiculously complex. Any help would be appreciated!

谢谢:)

推荐答案

const arr = [2, 2, 5, 2, 2, 2, 4, 5, 5, 9];

function foo (array) {
  let a = [],
    b = [],
    arr = [...array], // clone array so we don't change the original when using .sort()
    prev;

  arr.sort();
  for (let element of arr) {
    if (element !== prev) {
      a.push(element);
      b.push(1);
    }
    else ++b[b.length - 1];
    prev = element;
  }

  return [a, b];
}

const result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')
console.log(arr)

这篇关于计算数组元素的出现次数/频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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