Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
4.9. Count and group by a key
Easy
Topics
This question is in
4. Array utilitiesAn order history page lists orders under "Delivered", "Shipped" and "Cancelled". A tag cloud sizes each tag by how many posts use it. A contacts list groups people by the first letter of their name. These are two sides of one task: go through a list once, work out a key for each item, and either collect the items under their key or count them.
Write groupBy(array, iteratee) and countBy(array, iteratee) in groupBy.js, without Object.groupBy.
Signature
function groupBy(array, iteratee) // returns { key: [items…] }
function countBy(array, iteratee) // returns { key: count }iterateegives each item's key: a function, called asiteratee(item, index), or a property name such as"status", which meansitem.status.- Both return an object with no prototype (made with
Object.create(null)), likeObject.groupBydoes, so no inherited name can clash with a key.
Requirements
groupBymaps each key to an array of the items that have it;countBymaps each key to how many items have it.iterateecan be a function or a property name. A function is called once per item, with the item and its index.- Inside each group, items keep their input order, and they are the original items, not copies.
- Keys become property names, so they are strings:
1becomes"1", andtrue,nullandundefinedbecome"true","null"and"undefined". - The result has no prototype, and keys such as
"constructor","toString"and"__proto__"work like any other key. - An empty array gives an empty object (still without a prototype).
- The input is not changed.
Object.groupByandMap.groupByare not used.- 100,000 items are handled quickly.
Examples
const orders = [{ id: 1, status: "shipped" }, { id: 2, status: "delivered" }, { id: 3, status: "shipped" }];
groupBy(orders, "status");
// { shipped: [order 1, order 3], delivered: [order 2] }
countBy(orders, "status");
// { shipped: 2, delivered: 1 }groupBy([1.3, 2.1, 2.4], Math.floor); // { "1": [1.3], "2": [2.1, 2.4] }
countBy(["a", "bb", "cc"], (word) => word.length); // { "1": 1, "2": 2 }countBy(["constructor", "toString", "constructor"], (word) => word);
// { constructor: 2, toString: 1 }
groupBy([], "status"); // {} with no prototypeEnvironment
- Plain JavaScript in a browser page; the tests call the globals
groupByandcountByfromgroupBy.js. Object.groupByandMap.groupByare removed while the tests run. Keys are never symbols.
Hints
- With a plain
{}, what iscounts["constructor"]before you have counted anything? - How do you tell "no group for this key yet" from "a group exists"?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…