-4

I am trying to learn Javascript specifically the method, "filter()". I want to get an array of names from an array of objects. It just returns the same array of objects passed as an argument. What am I missing?

Update: I confused filter() with map(). I am sorry to waste people's time.

personsObj = {
 persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}

switchButtonHandler = (personsArray) => {
  var names = this.personsArray.persons.filter((obj) => obj.name);
  console.log(names);
}
heisenbaig
  • 133
  • 6
  • 1
    specifically, `filter` is the wrong tool for the job. You need `map`. – Alnitak Oct 12 '20 at 15:57
  • `.filter()` takes an array and potentially returns *less of the items*. It's filtering them by some predicate you supply. It doesn't *transform* the items, that is the job of `.map()` – VLAZ Oct 12 '20 at 15:58
  • 1
    p.s. either the name `personsArray` or the use of `{ ... }` is wrong, because the latter is an _object_. – Alnitak Oct 12 '20 at 16:01

1 Answers1

1

No, what you are trying to do is map an array to an array of other thing. In your case:

const personsArray = {
 persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}

const newArray = personsArray.persons.map(person => person.name) // use proper name

console.log(newArray)

Map is intended to transform an array into other different array and filter is intended to return an array based on a condition, like in this case "give me all the people with age higher than 18", so you could do:

const personsArray = {
 persons: [{name: "Baig",age: 14},{name: "HenTie", age: 20}]
}

const adults = personsArray.persons.filter(person => person.age > 18)

console.log(adults)
Agustin Moles
  • 1,364
  • 7
  • 15