What is the syntax in this filter method?

What is the syntax in this filter method?
0.0 0

#1

Could anybody help me explain the syntax of {name} in the following example?

When I use filter method, I always set the callback function as function(item){...} or item => {...}. But in the example, the author set the parameter of callback function as ({name}). What is the syntax rule?

function countBy(items, groupName) {

    let counts = [];
    for (let item of items) {
        let name = groupName(item);
        let known = counts.findIndex(c => c.name == name);
        if (known == -1) {
            counts.push({
                name,
                count: 1
            });
        } else {
            counts[known].count++;
        }

    }
    return counts;

}

let myArray = [1, 2, 3, 4, 5]; 

function moreThanTwo(n) {
    return n > 2;
}

console.log(countBy(myArray, moreThanTwo).filter(({name}) => name != false));
console.log(countBy(myArray, moreThanTwo).filter((item) => item.name != false)); // I would set the parameter in this way.

I come across this example in book Eloquent JavaScript (page 94) and make some alteration for clarification. The countBy function expects a collection (anything that we can loop over with for/of) and a grouping function. It returns an array of objects, each of which names a group and tells you the amount of elements that were found in that group.


#2

He is doing object destructuring, an ES6 feature.

He is saying "the CB in filter is being send an object with a property name - please take out that property and assign it to a variable called name.

The same thing could have been accomplished with:

console.log(countBy(myArray, moreThanTwo).filter((obj) => obj.name != false));

#3

Many thanks!:grinning:


#4

That’s why we’re here. :wink: