Examples
Write groupByLength so that the following cases hold.
- Input
groupByLength(["one","two","three","four"])Output{"3":["one","two"],"4":["four"],"5":["three"]} - Input
groupByLength([])Output{} - Input
groupByLength(["a"])Output{"1":["a"]}
Answer
js
function groupByLength(words) {
return words.reduce((acc, w) => {
(acc[w.length] ||= []).push(w);
return acc;
}, {});
}
groupByLength(["one", "two", "three"]);
// { 3: ["one", "two"], 5: ["three"] }
Object keys are always strings, so acc[3] and acc["3"] are the same bucket. An empty input returns {}, not [].
