[英]How to count same items with specail form in a array (javascript)
For example: 例如:
input: var arr = ['a','b','c','a-5','c-2'];
output: var result = {'a':6,'b':1,'c':'3'} ;
My solution is: 我的解决方案是:
function countSameItem(arr) {
var counter = {};
for (var i = 0; i < arr.length; i++) {
var item = arr[i].split('-');
if (item.length === 1) {
counter[item] = (counter[item] + 1) || 1;
} else {
counter[item[0]] = (counter[item[0]] + parseInt(item[1]) || parseInt(item[1]));
}
}
return counter;
}
But I want to thought a more consise solution using the lodash 但是我想考虑使用lodash的更简洁的解决方案
You can do it concisely without lodash: 您可以简明扼要地做到这一点:
var result = ['a','b','c','a-5','c-2'].reduce(function(o, s) {
var a = s.split('-').concat(1);
return o[a[0]] = (o[a[0]] || 0) + +a[1], o;
}, Object.create(null));
with lodash you would use the _.reduce function in a similar manner to the way Oriol uses the native reduce function 使用lodash时,您将以与Oriol使用本机reduce函数的方式类似的方式使用_.reduce函数
function countSameItem(arr) {
return _.reduce( arr, function(counter, n, i) {
var narr=n.split('-');
counter[narr[0]] = (counter[narr[0]] || 0) + (1*narr[1] || 1);
return counter;
}, {});
}
counter is the accumulator and what is eventually returned from the function. 计数器是累加器,该函数最终返回什么。
n is each element n是每个元素
i is the index of each element. i是每个元素的索引。
for each element in the input array counter gets the value returned by the last element that was ran. 对于输入数组中的每个元素,计数器获取由最后运行的元素返回的值。 The third argument in _.reduce gives the initial value of counter.
_.reduce中的第三个参数给出了counter的初始值。
Using the native implementation is probably better unless you are using lodash for other features and want consistency in the code. 除非您将lodash用于其他功能并且想要代码的一致性,否则使用本机实现可能会更好。
The lodash version of reduce does have the benefit of working on objects as well as arrays but this can be done natively as well by using Object.keys(arr).reduce reduce的lodash版本确实具有处理对象以及数组的好处,但这也可以通过使用Object.keys(arr).reduce本地完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.