0

I am having trouble with some basic javascript. I want this function to return an array of all objects within the given array that have the name "Ray" assigned to name. I can't get the push part to work.

  const people = [{name: "Jack", age: 30}, {name: "Ray", age: 32}, {name: "Anna", age: 28}]; 
  
function findRay(arr) {
  let response = []; 
  for(let i = 0; i < arr.length; i++) {
    if(arr[i].name === "Ray") {
      response.push(arr[i]); 
    }
  }
  return response;
}
  
console.log(findRay(people));  

6
  • 3
    Works fine for me, it returns an array with the Ray object. Commented Aug 3, 2017 at 19:06
  • Concur that it works. What browser are you using? Try changing const people = [......] to var people = [......] Commented Aug 3, 2017 at 19:08
  • I'm on Chrome. Also tried in Repl.it. This code does not work. Commented Aug 3, 2017 at 19:11
  • Works fine -> jsfiddle.net/adeneo/nm0566y2/1 ....... Commented Aug 3, 2017 at 19:12
  • 1
    Well, it does: repl.it/JwCl Maybe explain what do you mean with "does not work"? Commented Aug 3, 2017 at 19:13

1 Answer 1

2

While not exactly what you were looking for, this is a good use case for filter(). So you could do something like const findRay = arr => arr.filter(person => person.name === "Ray").

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.