转换数组新阵列(计数出现) [英] Convert Array to new Array (counting occurrences)

查看:119
本文介绍了转换数组新阵列(计数出现)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组的 N 项目数量

I have an array of n number of items

var arr1 = [2, 0, 0, 1, 1, 2, 0, 0, 0, 2, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2, 1, 2, 2, 0, 1, 2, 2, 1, 1, 0, 1, 1, 0, 2, 1, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 0, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 0, 2, 2, 0, 2, 0, 0, 1, 2, 1, 0, 2, 1, 0, 1, 2, 0, 2, 0, 0, 0, 1, 2, 1, 0, 2, 0, 0, 0, 1, 2, 1, 1, 1, 1]

当你看到数组只有不同的值(V) (0,1,2), I = 3 在这种情况下

as you see the array only has i different values (v) (0,1,2),i = 3 in that case

我想与像这样的一个数组结束了一下。

What I would like is ending up with an array like this one.

var arr2 = [23, 45, 64]

在ARR2数组的长度应符合和值前人的精力是每个值的OCCURENCES (V)

the length of the arr2 array should corresponds to i and the values sould be the occurences of each value(v)

我做各种循环和条件,但寻找一个直的解决方案。
我的一部分,到目前为止 http://jsfiddle.net/fiddlebjoern/aSsjy/2/

I am doing all kinds of loops and conditionals, but looking for a straight solution. my part so far http://jsfiddle.net/fiddlebjoern/aSsjy/2/

jQuery和/或下划线均可受累。

jQuery and/or underscore may be involved.

推荐答案

易peasy!您输入的值将成为您的输出的钥匙;你积累在琴键上,你遇到的值:

Easy peasy! The values of your input become the keys of your output; you accumulate on those keys as you encounter the values:

var arr1 = [0,0,0,1,2,3,4,3,2,3,4,3,4,3,5];
var arr2 = [];

for (var i = 0; i < arr1.length; i++) {
   var n = arr1[i];
   if (arr2[n] != undefined)
       arr2[n]++;
   else
       arr2[n] = 1;
}

console.log(arr2);  // Output: [3, 1, 2, 5, 3, 1]

这篇关于转换数组新阵列(计数出现)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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