Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Startswith function for searching an array

Tags:

javascript

I have a function that is giving me some trouble. The code below returns the error message "Cannot read property 'value' of undefined". The function should just search through the values in the accountlist and return the one that starts with the submitted string. In the example, submitting "000555" should return 0.

var accountlist = [{
    "value": "000555 - TEST ACCOUNT NAME1",
    "data": "184"
}, {
    "value": "006666 - TEST ACCOUNT NAME2",
    "data": "450"
}, {
    "value": "007777 - TEST ACCOUNT NAME2",
    "data": "451"
}];

function startswith(inputlist, searchkey, inputstring) {
    var searchlength = inputstring.length;
    console.log("starting search");

    for (var il = 0; il < inputlist.length; il++) {
        if (inputlist[il].window[searchkey].substring(0, (searchlength - 1)) == inputstring) {
            console.log("FOUND IT " + il + "      " + inputstring);
            return il
        }
    }
}

startswith(accountlist, "value","000555");
like image 791
keatklein Avatar asked Feb 04 '23 11:02

keatklein


1 Answers

You could use the find function:

var accountlist = [{
    "value": "000555 - TEST ACCOUNT NAME1",
    "data": "184"
}, {
    "value": "006666 - TEST ACCOUNT NAME2",
    "data": "450"
}, {
    "value": "007777 - TEST ACCOUNT NAME2",
    "data": "451"
}];
var searchString = '000555';
var result = accountlist.findIndex((account) => { return account.value.startsWith(searchString);}, searchString)
console.log(result)
like image 141
funcoding Avatar answered Feb 07 '23 13:02

funcoding