0

i reading through JavaScript Eloquent and came across a code snippet which it doesn't explain how this works

  let scripts = countBy(text,char => { 
    let script = characterScript(char.codePointAt(0))
    return script ? script.direction : "none";
   }).filter(({name}) => name != "none")
  return scripts

}
function countBy(items, groupName) {
  let counts = [];
  for (let char of text) {
    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;
}

so this is what i cant get my head around how it works, .filter(({name}) => name != 'none')

how does this pull the local variable from within a function and can use it to filter by this variable? and why does it have to be between theses ({})?

Jperkins98
  • 67
  • 1
  • 10
  • 2
    It's called object destructuring:- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Addis Feb 05 '20 at 20:52
  • 3
    `name` isn't a local variable, it's a property of the object being passed to the `.filter` function, and then automatically destructured to create a parameter of that name. – Alnitak Feb 05 '20 at 20:53
  • to complement above comments, see [documentation of object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring) – Calvin Nunes Feb 05 '20 at 20:54
  • 1
    It may be a little easier to understand if you take one step back and skip the destructuring: `.filter((countObject) => countObject.name != "none")` – pcrglennon Feb 05 '20 at 21:10

0 Answers0