在Javascript中,我试图采取数字值的初始数组,并计算其中的元素。理想情况下,结果将是两个新数组,第一个数组指定每个唯一元素,第二个数组包含每个元素出现的次数。但是,我愿意听取关于输出格式的建议。
例如,如果初始数组是:
5, 5, 5, 2, 2, 2, 2, 2, 9, 4
然后将创建两个新数组。第一个将包含每个唯一元素的名称:
5, 2, 9, 4
第二个将包含该元素在初始数组中出现的次数:
3, 5, 1, 1
因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。
我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!
谢谢:)
根据@adamse和@pmandell的回答(我支持),在ES6中,你可以在一行中完成:
2017年编辑:我使用||来减少代码大小,使其更具可读性。
var =[7, 1、7、2、2、7、3、3、3、7、7、7、7];
警报(JSON.stringify (
a.reduce ((r, k) = > {[k] = 1 + r [k] | | 1;返回r}, {})
));
它可以用来计数字符:
var s =“唵嘛呢叭咪吽”;
警报(JSON.stringify (
s.split(”)。Reduce ((a, c)=>{a[c]++?0:a[c]=1;返回a},{})
));
使用减法和波浪号(~)操作符的较短版本。
Const data = [2,2,2,2,2,2,4,5,5,5,9];
函数频率(nums) {
num返回。Reduce ((acc, curr) => {
Acc [curr] = -~ Acc [curr];
返回acc;
}, {});
}
console.log(频率(数据));
如果你使用下划线,你可以走功能路线
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>
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 array = [ 'a', 'b', 'b', 'c', 'c', 'c' ];
你可以使用这个简单的一行代码来生成一个哈希映射,将一个键链接到它在数组中出现的次数:
const hash = Object.fromEntries([ ...array.reduce((map, key) => map.set(key, (map.get(key) || 0) + 1), new Map()) ]);
// { a: 1, b: 2, c: 3 }
扩展和解释:
// first, we use reduce to generate a map with values and the amount of times they appear
const map = array.reduce((map, key) => map.set(key, (map.get(key) || 0) + 1), new Map())
// next, we spread this map into an array
const table = [ ...map ];
// finally, we use Object.fromEntries to generate an object based on this entry table
const result = Object.fromEntries(table);
这个数组归功于@corashina。减少代码