Write a function “groupBy(array, callback)”

前端 未结 7 1019
醉梦人生
醉梦人生 2020-12-06 19:52

I have a JavaScript task where I have to implement a function \"groupBy\", which, when given an array of objects and a function, returns an object w

7条回答
  •  一生所求
    2020-12-06 20:41

    It's a reduce() one-liner. Reduce allows you to loop through the array and append to a new object based on the logic of its callback. In this function a (for accumulated) is the object we're making and c (for current item) is each item in the loop taken one at a time.

    It works especially concisely here because the function to make the object key is passed in:

    var list = [{id: "102", name: "Alice"},
    {id: "205", name: "Bob", title: "Dr."},
    {id: "592", name: "Clyde", age: 32}];
    
    function groupBy(list, Fn) {
        return list.reduce((a, c) => (a[Fn(c)] ? a[Fn(c)].push(c) : a[Fn(c)] = [c], a), {})
    }
    
    var t = groupBy(list, function(i) { return i.id; });
    console.log(t)
    
    var l = groupBy(list, function(i) { return i.name.length; });
    console.log(l)

提交回复
热议问题