countBy Method into a Function using Javascript

I'm trying to write a countBy function, identical to the countBy method in Javascript. Here is what I have so far:

var array = [1,2,4,4,5];
function countBy(collection, func) { var object = {} ; for (var i=0;i<=0; i++) { for (var key in object) { if (func(collection[i]) === object.key) { object.key ++; } else { object.key = 1; } } } return object
}
alert(countBy(array, function(n) {return Math.floor(n);}));

What the code intends to do is search through the collection array to see if a value there matches a key in object. If it has found a match in the collection array, increment that key value by one. If it has not found one, create a new key value. Therefore, the result that should be alerted is: {4:2, 1:1, 2:1, 5:1}. But it seems like my output is [object Object]. What am I doing wrong??

2 Answers

for (var i=0;i<=0; i++) {

This will run exactly once instead of iterating through the collection.

for (var key in object) { if (func(collection[i]) === object.key) {

This does the wrong thing; you should call func only once in each iteration and then look up the result of the function call in your object.

object.key ++;

This doesn't do what you want; it's better to use the array dereference operator instead.

function countBy(collection, func)
{ var object = Object.create(null); collection.forEach(function(item) { var key = func(item); if (key in object) { ++object[key]; } else { object[key] = 1; } }); return object;
}
function countby(arr, selector) { selector = selector ?? (x => x) // default is identity const f = (acc, x) => { let k = selector(x); acc[k] = (acc[k] ?? 0) + 1; return acc } return arr.reduce(f, {})
};
let r
r = countby([2, 3, 1, 3, 4, 4])
console.log(r)
r = countby([{a:2}, {a:3, b:"bunny"}, {a:2}], (x => x.a))
console.log(r)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like