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.