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

例如,如果初始数组是:

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

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

5, 2, 9, 4

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

3, 5, 1, 1

因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。

我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!

谢谢:)


当前回答

ES6版本应该更简单(另一个一行解决方案)

let arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
let acc = arr.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());

console.log(acc);
// output: Map { 5 => 3, 2 => 5, 9 => 1, 4 => 1 }

Map代替普通对象帮助我们区分不同类型的元素,否则所有计数都是基于字符串

其他回答

你可以使用一个对象来保存结果:

Const arr = [5,5,5,2,2,2,2,2,2,2,2,9,4]; Const counts = {}; (const num of arr) { Counts [num] = Counts [num] ?计数[num] + 1: 1; } console.log(重要); Console.log(计数[5],计数[2],计数[9],计数[4]);

所以,现在你的counts对象可以告诉你一个特定数字的计数是多少:

console.log(counts[5]); // logs '3'

如果您想获取成员数组,只需使用keys()函数即可

keys(counts); // returns ["5", "2", "9", "4"]

这里有一些对眼睛来说简单的东西……

function count(a,i){
 var result = 0;
 for(var o in a)
  if(a[o] == i)
   result++;
 return result;
}

编辑:既然你想要所有的事件……

function count(a){
 var result = {};
 for(var i in a){
  if(result[a[i]] == undefined) result[a[i]] = 0;
  result[a[i]]++;
 }
 return result;
}

如果你使用下划线,你可以走功能路线

a = ['foo', 'foo', 'bar'];

var results = _.reduce(a,function(counts,key){ counts[key]++; return counts },
                  _.object( _.map( _.uniq(a), function(key) { return [key, 0] })))

第一个数组是

_.keys(results)

第二个数组是

_.values(results)

如果本地javascript函数可用,其中大部分将默认为本地javascript函数

演示:http://jsfiddle.net/dAaUU/

查看下面的代码。

<html>
<head>
<script>
// array with values
var ar = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

var Unique = []; // we'll store a list of unique values in here
var Counts = []; // we'll store the number of occurances in here

for(var i in ar)
{
    var Index = ar[i];
    Unique[Index] = ar[i];
    if(typeof(Counts[Index])=='undefined')  
        Counts[Index]=1;
    else
        Counts[Index]++;
}

// remove empty items
Unique = Unique.filter(function(){ return true});
Counts = Counts.filter(function(){ return true});

alert(ar.join(','));
alert(Unique.join(','));
alert(Counts.join(','));

var a=[];

for(var i=0; i<Unique.length; i++)
{
    a.push(Unique[i] + ':' + Counts[i] + 'x');
}
alert(a.join(', '));

</script>
</head>
<body>

</body>
</html>

ECMAScript2015选项怎么样?

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

const aCount = new Map([...new Set(a)].map(
    x => [x, a.filter(y => y === x).length]
));
aCount.get(5)  // 3
aCount.get(2)  // 5
aCount.get(9)  // 1
aCount.get(4)  // 1

这个例子将输入数组传递给Set构造函数,创建一个唯一值的集合。然后,扩展语法将这些值展开为一个新数组,这样我们就可以调用map并将其转换为一个[value, count]对的二维数组——即如下结构:

Array [
   [5, 3],
   [2, 5],
   [9, 1],
   [4, 1]
]

然后将新数组传递给Map构造函数,得到一个可迭代对象:

Map {
    5 => 3,
    2 => 5,
    9 => 1,
    4 => 1
}

Map对象的伟大之处在于它保留了数据类型——也就是说account .get(5)将返回3,但account .get("5")将返回未定义。它还允许任何值/类型作为键,这意味着该解决方案也适用于对象数组。

函数频率(/*{数组}*/ a){ 返回新地图([…]新组(a)] . map ( X => [X, a.filter(y => y == X).length] )); } 让foo = {value: 'foo'}, Bar = {value: ' Bar '}, Baz ={值:' Baz '}; let aNumbers = [5,5,5,2,2,2,2,2,2,2,2,9,4], aObjects = [foo, bar, foo, foo, baz, bar]; 频率(许多)。forEach (val关键)= > console.log(关键 + ': ' + val)); 频率(aObjects)。forEach((val, key) => console.log(key. log)Value + ': ' + val));