1

I have alphabetically ordered list of countries in an array like following:

[
  {
    name: "United States",
    country_code: "US",
    dial_code: "+1"
  },
  { .. etc }
]

I am listening for users key input and lets say they press "a" key. I want to get index of first object in the array where name starts with "a".

Now my question is not to how to perform this whole operation, just advice / ideas on how to find such index in the array if I already know user pressed "a". I was looking into lodash to do this, but wasn't able to figure it out, hence feel free to use third party libraries if they are appropriate to solve this.

4 Answers 4

1

use _.findIndex to find first matched item index:

var firstIndex = _.findIndex(countries, function(country) {
    return _.chain(country)
        .get('name', '')
        .lowerCase()
        .startsWith('a')
        .value();
});
Sign up to request clarification or add additional context in comments.

Comments

1

You could use an object with the first letter and an index for the access to the given array and end of the array with the same letter, like

var abc = {
    u: [0, 1]
}

Example with letter 'u':

var countries = [{ name: "United Kingdom", country_code: "UK", dial_code: "+44" }, { name: "United States", country_code: "US", dial_code: "+1" }, { name: "France", country_code: "FR", dial_code: "+33" }, { name: "Italy", country_code: "IT", dial_code: "+16" }],
    abc = Object.create(null);

countries.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});

countries.forEach(function (a, i) {
    var c = a.name[0].toLowerCase();
    if (!abc[c]) {
        abc[c] = [i];
    }
    abc[c][1] = i + 1;
});

console.log(Array.prototype.slice.apply(countries, abc['u']));
console.log(abc);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You could implement a function that would filter countries which name start with the letter given as parameter :

var countries = [
  {
    name: "United States",
    country_code: "US",
    dial_code: "+1"
  },
  {   name: "France",
    country_code: "FR",
    dial_code: "+33"
  },
  {   name: "Italy",
    country_code: "IT",
    dial_code: "+16"
  }
]
var selectedCountries = (array, letter) => array.filter(x => x.name.indexOf(letter) === 0);

console.log(selectedCountries(countries, "F"));

Comments

0

If older browsers aren't an issue, you can combine Array.find and String.startsWith

var obj = arr.find( x => x.name.startsWith('a'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.