0

Let's say I have an array of objects

const arr = [ {name:"Bob", age: 20}, { name: "Sara", age: 22}, { name:
Tom, age:20} ];

I want to print objects with particular property, for example only those with the age == 20. So The result would be

const arr = [ {name:"Bob", age: 20}, { name: Tom, age:20} ];

I really want to do it with ES6. Do you have any suggestion what method could be used?

demongolem
  • 9,474
  • 36
  • 90
  • 105
Etoya
  • 239
  • 1
  • 7
  • 16

1 Answers1

4

This will do

var filteredData = arr.filter((e) => e.age === 20)
Ishwar Patil
  • 1,671
  • 3
  • 11
  • 19
  • could you explain a bit how it does the trick? – Patrick Hund May 10 '17 at 14:50
  • filter() is a function available on Array now. It iterates the complete array and returns the value which is matching the condition. In above case age==20. => function from ES6 provides a short cut here...so that you do not need to explicitly 'return' the value. It will do it automatically (if you have only one line of code inside it). – Ishwar Patil May 10 '17 at 14:52
  • For more detail and example, you can read it on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=example – taile May 10 '17 at 15:24
  • I meant explain in the answer, but never mind, closed as duplicate – Patrick Hund May 10 '17 at 16:43