score:1

Accepted answer
const countries = [{ id: 2, code: "AL", name: "Albania" }, { id: 3, code: "DZ", name: "Algeria" }, { id: 4, code: "DS", name: "American Samoa" }];
function getCountryId(code) {
  const country = countries.filter(country => country.code === code);
  if(country.length > 0) {
    return country[0].name;
  } else {
    return "No such country.";
  }
}
console.log(getCountryId("DZ"));
console.log(getCountryId("USA"));

score:0

 var data = [{ id: 2, code: "AL", name: "Albania" }, { id: 3, code: "DZ", name: "Algeria" }, { id: 4, code: "DS", name: "American Samoa" }]

Array.prototype.getCountryID = function(code){
  var output = this.filter(el => el.code === code);
  return output.length > 0 ? output[0].id : "Not Found";
}

console.log(data.getCountryID("DS"));
console.log(data.getCountryID("something else"));

score:1

const list = [{
  id: 2,
  code: "AL",
  name: "Albania"
}, {
  id: 3,
  code: "DZ",
  name: "Algeria"
}, {
  id: 4,
  code: "DS",
  name: "American Samoa"
}];


function getCountryId(name) {
  return (list.filter((country) => country.name === name)[0] || {}).id;
}


console.log(getCountryId('Algeria'));
console.log(getCountryId('NoneExistingCountry'));

score:3

const country = array.getCountry("USA");

console.log(country && country.id);

Related Query

More Query from same tag