Search code examples
javascriptarraysassociative-array

Get Array Index Key - Javascript


The problem

I am iterating over a states array the looks like this

let states = [
                ['AL', 0],
                ['AK', 0],
                ['AZ', 0],
                ['AR', 0],
                ['CA', 0]......
]

and comparing it to states array that actually has values after the state code. I have a function that is trying to merge both array by checking the first array and seeing if the key (state) exists in the second array. If it does it should replace that array with the array found in the second array.

I've tried

Below is my attempt, it clearly does not work, I have tried shifting the array index and getting just the state code, but that throws an undefined error.

function mergeArrays(arr1, arr2) {
        for(let i = 0; i < arr1.length; i++) {
            let arr1state = arr1[i];
            let arr2state = arr2[i];
            if (arr1state === arr2state) {
                console.log(arr1[i], arr2[i])
            }
        }
    }

Solution

  • I'd iterate over the actual states, the ones which have the correct values, and put them in a map.

    Then iterate the states array and just check if your desired value exists in said map.

    let states = [['AL', 0],
                    ['AK', 0],
                    ['AZ', 0],
                    ['AR', 0],
                    ['CA', 0]];
    
    let actualStates = [['AL', 1],
                    ['AK', 2],
                    ['AZ', 3],
                    ['CA', 4]];
    
    function merge(states, actualStates){
        let map = {};
        for(let actualState of actualStates) map[actualState[0]] = actualState[1];
        for(let state of states) state[1] = map[state[0]] || state[1];
        return states;
    }
    
    console.log(merge(states, actualStates));