Using .find() array method

Hello everyone
given this array of objects

const record = [
    { year: "2018", result: "N/A"},
    { year: "2017", result: "N/A"},
    { year: "2016", result: "N/A"},
    { year: "2015", result: "W"},
    { year: "2014", result: "N/A"},
    { year: "2013", result: "L"},
]

I wanted to use .find() method to return the year if the resulting key matched "W" and and undefined if not , this is my function to do that

 function superbowlWin(record) {
    
   if (record.result === "W") {
    return (record.year)
   } else {
    return undefined 
   }
}
const finalResult = record.find(superbowlWin)

but when I executing it its not return the desired value
any help will be appreciated :dizzy:

find will return the element of the array, whatever you do in the callback function. Make sure the function returns true for the array element you want to find and false otherwise

1 Like

If you look at the documentation for the .find() method it says:

The callback must return a truthy value to indicate a matching element has been found.

So I believe you will want to do something more like this:

const results = [
    { year: "2018", outcome: "N/A"},
    { year: "2017", outcome: "N/A"},
    { year: "2016", outcome: "N/A"},
    { year: "2015", outcome: "W"},
    { year: "2014", outcome: "N/A"},
    { year: "2013", outcome: "L"},
];

Solution redacted by mod
1 Like

I have redacted part of the code you shared in your post because it is considered to be sharing a solution with the original poster. We are trying to share tips/hints but not solutions when people post on the forum asking for help. Thanks for your understanding.

1 Like

you only want the first element with ‘W’, or possibly multiple elements (years)?
https://devdocs.io/javascript/global_objects/array/find

1 Like

hey @ugwen i just wanted it to return the year when the result it’s “W”

The function should receive 1 argument, an Array of JavaScript Objects
Each object has two properties: year and result
It should use find() to test each Object to see if the result is "W" — a win!
It should return the year when the win occurred (if it occurred at all!)
If no win is found, it should return, sadly, undefined

ah my apologies! i will make sure to mind that line closer from now on.

1 Like

find() only returns the first element it finds (looking in index order). so you need to use it on each element in case there are multiple elements that pass true.
sorry, didn’t take a look at problem/code, it is easier if you use ‘get help’ option which will automatically include code and link to exercise.

Thnks for your reply @ugwen actualy
its not a part of freeCodeCamp exercise

1 Like

ok. well rememba you can add .year to the end of the expression to return just the year. (not sure you need that tho)
record.find(superbowlWin).year

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.