2

I have a function that needs to return the id of a country.

My list is an array of objects :

{
    id: 2,
    code: "AL",
    name: "Albania"
}...

Here is my function to get the id needed from country

getCountryID(countryName) {
            return country_list_with_id.forEach(res => {
                if (res.name.toLowerCase() === countryName) {
    console.log("the id is",res.id)// the log is 143
                    let id = res.id;
                    return id;
                }
            });
        }
    console.log(array.getCountryID("USA"))//undefined

so how could I get the id?

jadlmir
  • 465
  • 1
  • 6
  • 16
  • 1
    Possible duplicate of [Can forEach in JavaScript make a return?](https://stackoverflow.com/questions/32041912/can-foreach-in-javascript-make-a-return) – Aaron Christiansen Mar 09 '18 at 10:46
  • `toLowerCase() === countryName` `countryName = "USA"` never going to happen.. – Keith Mar 09 '18 at 10:49

4 Answers4

3

You can't. forEach is not intended to return anything, but you can use another function to get the id from the array.

Using find will return you an object which is satisfies your condition.

getCountry(countryName) {
    return country_list_with_id.find(item => item.name.toLowerCase() === countryName);
}

This will return the country object and from that object you can inject the id. If nothing was found, undefined is returned. So you need to check that object first, then try to access its properties.

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

console.log(country && country.id);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • This is the most logical solution if you don't care about prehistoric browsers :-) Nice job. – enf0rcer Mar 09 '18 at 10:52
  • @user3492940 `if you don't care about prehistoric browsers` On SO, we don't. For these outdated & security issued browsers, we pollyfill & transpile.. :) – Keith Mar 09 '18 at 10:54
  • Recently I have read a blog where a person says that you don't need to care about prehistoric browsers, force them to upgrade the browser :). Nevertheless Javascript must go to the production with transpiled version and polyfills – Suren Srapyan Mar 09 '18 at 10:54
  • @SurenSrapyan Indeed, otherwise we would be spending 50% of our time answering questions by having code to show how it's done in older browsers. IMO: All answers unless the OP says otherwise should assume ES6 is fine. – Keith Mar 09 '18 at 10:57
  • Not saying you should care about them, but something worth mentioning because not everyone has the luxury of ignoring the dinosaurs among us. – enf0rcer Mar 09 '18 at 12:50
1

You can filter your array of countries to get the country you want, and return result. countries[0] might be undefined so use an if statement from my example or ternary operator from @void's example Here's the snippet:

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"));
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18
1

You can use Array.prototype.filter in order to filter out the country by name, and then return the id of the first/last item.

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'));
felixmosh
  • 32,615
  • 9
  • 69
  • 88
0

Use need to use .filter here. This will return the items from array matching specific condition

 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"));
void
  • 36,090
  • 8
  • 62
  • 107