dis*_*dng 1 javascript underscore.js
我目前对JS和下划线都很陌生.我想看看给定数组中哪个特定数字最多,(现在说var a).作为狂热的python用户,我习惯在频率电报中对其进行求和,然后将其输出为元组[(1,3),(2,2),...],然后将其排序.
在javascript中这样做的最佳方法是什么?
function votesTied() {
var a = [1, 2, 3, 1, 2, 4, 6, 1, 7];
var tele = {};
_.each(a, function(key) {
if (tele[key]) {
tele[key]++;
} else {
tele[key] = 1;
}
});
var items = _.map(tele, function(frequency,key) { return [key,frequency]; });
var results = _.sortBy(items, function(tuple) { return -1 * tuple[1]; }).value();
return results.length > 1 && results[0][1] == results[1][1];
}
Run Code Online (Sandbox Code Playgroud)
我这么问,因为我可以在1行python中完成所有这些.我确信有一种更优雅的方式用下划线或javascript写这个.
令人遗憾的是,下划线的map()函数无法返回具有维护属性的对象,因为这样可以实现以下内容:
var t = _.chain (a)
.groupBy (function (p) { return p; })
.map (function (e) { return _.size (e); })
.value ();
Run Code Online (Sandbox Code Playgroud)
但是如果没有重写函数来实现这一点,我能想到的最好的是:
var t = {};
_.chain (a)
.groupBy (function (p) { return p; })
.each (function (e, i) {
t[i] = _.size (e);
});
Run Code Online (Sandbox Code Playgroud)
这将收集所有内容t.
UPDATE
我不能让它可以了,所以我查源下划线的map(),并提出以下修改,以允许第一个片段之上:
_.map = function(obj, iterator, context) {
// determine the return type
if (_.isArray (obj)) {
var results = [];
}
else {
var results = {};
}
if (obj == null) return results;
// @xxx: we need to override the native map(), thus the next line is commented out
// if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[index] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
Run Code Online (Sandbox Code Playgroud)
我没有彻底检查过,但它应该工作.