0

I am a student. I'm trying to return one element based on one other. I need to use .find to search for the result "W" (the year a sports team won) and return the corresponding year. I'm expected to write function (superbowlWin(record) in order to satisfy this.

const record = [
{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "W"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "L"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}
]
Michael
  • 169
  • 3
  • 11
  • 3
    also see: [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – pilchard Nov 24 '21 at 14:29

2 Answers2

0

The array method filter and find make a good job for this task. Both you will find below:

const record = [
{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "W"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "L"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}
]

let r = [];
r1 = record.filter(x => x.result === 'W');
console.log('result filter: ',r1)
r2 = record.find(x => x.result === 'W');
console.log('result find: ',r2)
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
-1

Adding JSFiddle for ref https://jsfiddle.net/ug70xL4y/

const record = [{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "W"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "L"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}];

function superbowlWin(records) {
let el = records.find(e=>e.result==='W');
if(el){
return el.year;
}else{
return undefined;
}
}
superbowlWin(record);
Diwakaran
  • 22
  • 3