开发者

Does JavaScript or jQuery have a function similar to Excel's VLOOKUP?

开发者 https://www.devze.com 2023-02-14 22:25 出处:网络
Do JavaScript or jQuery have a function that returns the element of an array whose index equal to the position of a given value in another array? (I could write my own, but I don\'t want to reinvent t

Do JavaScript or jQuery have a function that returns the element of an array whose index equal to the position of a given value in another array? (I could write my own, but I don't want to reinvent the wheel.)

Something like:

function vlookup(theEl开发者_StackOverflowement, array1, array2) {
    $.each(array1, function(index, element) {
        if (element === theElement)
            return array2[index];
    });
    return null;
}

But, um... in the standard library.


Something like this perhaps?

Array.prototype.vlookup = function(needle,index,exactmatch){
    index = index || 0;
    exactmatch = exactmatch || false;
    for (var i = 0; i < this.length; i++){
        var row = this[i];

        if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1)
            return (index < row.length ? row[index] : row);
    }
    return null;
}

Then you can use it against a double array, like so

Depending your purpose, you can modify the indexOf to make both strings lowercase first so the comparison doesn't fail with "foo" vs "FOO". Note also that if index exceeds the row's length, the entire row is returned (this can be changed to the first element (or whatever) easily by modifying the : row); portion.

0

精彩评论

暂无评论...
验证码 换一张
取 消