简体   繁体   中英

Javascript .find using one element to return another

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"}
]

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM