Home > Back-end >  how do I check an array of tuples for a value in index[0] and if there is a match, display the value
how do I check an array of tuples for a value in index[0] and if there is a match, display the value

Time:07-20

I have an array of tuples:

var tuparray: [string, number][];
 tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]];

const addressmatch = tuparray.includes(manualAddress);

I want my function to check if the tuparray contains a user input (string), manualAddress. If it finds a match in any of the tuples, it should display the value from the number at [1] of the tuple.

if (addressmatch){
console.log("address qualifies for [matched tuple number here]");

Any help on this would be greatly appreciated!

CodePudding user response:

Just use find() on the Array and provide a lambda function to evaluate the match.

var tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]];

function includes(manualAddress) {
    const found = tuparray.find(x => x[0] == manualAddress)
    
    if (found) {
        console.log(`address qualifies for ${found[1]}`)
    } else {
        console.log(`Not found`)
    }
}

includes('0x123')
includes('0x456')
includes('0x111')
  • Related