Ilja Ilja - 9 months ago 51
JSON Question

Getting index of first object in an array that has "name" property starting with selected letter

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.

Answer Source

use _.findIndex to find first matched item index:

var firstIndex = _.findIndex(countries, function(country) {
    return _.chain(country)
        .get('name', '')