0

i know my description is a little bit confusing but let me explain you: I have an array of objects likes this: [{name: Alex, last: Huros}, {name: Mitsos, last: Mitsou},name: Bill, last: Hurosis ]

I have a variable which value is const name = Alex. Now i want to find the last where the name=Alex. To be more specific i want to find the name = Alex with some way or generaaly given the name i want to find the last for this name. How to do this? I've tried array.forEach and find but didn't work the way i use it

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
RamAlx
  • 6,976
  • 23
  • 58
  • 106

1 Answers1

1

You should use find method, which returns the value of the first element in the array that satisfies the provided callback function. Otherwise undefined is returned.

var array=[{"name": "Alex", "last": "Huros"}, {"name": "Mitsos", "last": "Mitsou"},{"name": "Bill", "last": "Hurosis" }]
console.log(array.find(function(person){
  return person.name=="Alex";
}).last);

Or simply use arrow functions.

var last = array.find(p => p.name === 'Alex').last;
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128