Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Monday, January 9, 2017

PlainJS: Search Array For Specific Value


.
PlainJS: Search Array For Specific Value
Plain Java Script: Search Array For A Specific Value
JS
var Person = function(code, name) {
    this.code = code;
    this.name = name;
};
var people = [
    new Person("ABC123", "Tooth Fairy"),
    new Person("DEF456", "Santa Claus"),
    new Person("PIR000", "Jack Sparrow"),
    new Person("XYZ987", "Easter Bunny")
    ];
// create a function on the Array prototype directly
Array.prototype.findInArray  = function(searchFor, property) {
    var retVal = -1;
    var self = this;
    for(var index=0; index < self.length; index++){
        var item = self[index];
        if (item.hasOwnProperty(property)) {
            if (item[property].toLowerCase() === searchFor.toLowerCase()) {
                retVal = index;
                return retVal;
            }
        }
    };
    return retVal;
};
// let's use the prototype for now
var i = people.findInArray("abc123", "code");
document.getElementById("output").innerHTML=JSON.stringify(people);
document.getElementById("output").innerHTML+="<br/>";
document.getElementById("output").innerHTML+="Searching NAME for CODE abc 123";
document.getElementById("output").innerHTML+="<br/>";
document.getElementById("output").innerHTML+="index="+i;
document.getElementById("output").innerHTML+=":";
document.getElementById("output").innerHTML+="name="+(people[i].name);
If not found i=-1.
.

No comments:

Post a Comment