0

I have a function that changes an object for me and I'm wondering how a bit of it works and would be grateful if someone could explain it or point me in the right direction. Here is the function:

$scope.filteredObject = Object.keys($scope.filterObject).reduce(function(p, collection) {
    var values = $scope.filterObject[collection];
    p[collection] = Object.keys(values).filter(function(key) {
        return values[key] === true;
    }).map(function(key) {
        return key;
    });
    return p;
}, {});

So this works great, but I'm wondering what the }, {}); at the end of the function does exactly. Im not exactly sure the name of that and googleing "}, {} after a function in javascript" seems to confuse the hell out of google (lol). Thanks!

3
  • 1
    It's .reduce(function(p, collection) { ... }, {}); In other words, the rest of the .reduce() function call. Commented Apr 15, 2015 at 0:38
  • The anonymous function and the empty object ({}) are parameters to the reduce function. Commented Apr 15, 2015 at 0:38
  • MDN Reduce Commented Apr 15, 2015 at 0:39

2 Answers 2

3
  • } - end of the anoymous function expression function(p, collection) { … }
  • , - delimiter between multiple arguments
  • {} - (empty) object literal, the second argument
  • ) - end of function invocation, closing parentheses for the arguments list to .reduce(…)
Sign up to request clarification or add additional context in comments.

Comments

1

It is an empty object and has nothing to do with the function. Have a look at the Array.prototype.reduce()

The reduce function has a second optional parameter.

arr.reduce(callback[, initialValue])

So in your case it's like this:

callback = function(p, collection) { /*...*/ };
initialValue = {}; // could also be new Object()

Hope this helps :)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.