简体   繁体   English

获取数组索引键 - Javascript

[英]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])
            }
        }
    }

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.然后迭代states数组并检查您想要的值是否存在于所述地图中。

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));

You are comparing two arrays against each other, not their keys, what you should compare is arr1state[0] === arr2state[0] , otherwise you would be just checking ['AL', 0] === ['AL', 13] , for example, as arr1state actually holds ['AL', 0] for i = 0 .您正在比较两个数组,而不是它们的键,您应该比较的是arr1state[0] === arr2state[0] ,否则您将只是检查['AL', 0] === ['AL', 13] ,例如,因为arr1state实际上为i = 0持有['AL', 0]

However, there's also the problem that you are expecting both arrays to have the same length, and be in the same order, to fix this you need to iterate the entire second array looking for that one state key, for every element in the first array.但是,还有一个问题是您希望两个数组具有相同的长度,并且顺序相同,要解决此问题,您需要迭代整个第二个数组以查找一个状态键,对于第一个数组中的每个元素. So, something like this:所以,像这样:

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

This example doesn't actually do the merging, as you didn't mention if you want to just replace it, or what should happen if only one of them has a value, however it should already answer your question of what's wrong, and allow you to fix your code.这个例子实际上并没有进行合并,因为你没有提到你是否只想替换它,或者如果只有一个有值会发生什么,但是它应该已经回答了你的问题,并允许你来修复你的代码。

Iterate over the first array of states & find the corresponding array in the second array of states (you can use reduce to do that):迭代第一个状态数组并在第二个状态数组中找到相应的数组(您可以使用reduce来做到这一点):

 const states1 = [ ['AL', 0], ['AK', 0], ['AZ', 0], ['AR', 0], ['CA', 0], ] const states2 = [ ['AL', 1], ['AZ', 3], ['CA', 5], ] const mergeStates = ({ arr1, arr2 }) => { // iterate over the first array: return arr1.reduce((a, [state1, val1]) => { // find the corresponding item in the second array: const item = arr2.find(([state2]) => state1 === state2) // check if item exists if (item) { const [_, val2] = item a = [...a, [state1, val2]] } else { a = [...a, [state1, val1]] } return a }, []) } const merged = mergeStates({ arr1: states1, arr2: states2 }) console.log(merged)


Or a simpler solution:或者更简单的解决方案:

 const states1 = [ ['AL', 0], ['AK', 0], ['AZ', 0], ['AR', 0], ['CA', 0], ] const states2 = [ ['AL', 1], ['AZ', 3], ['CA', 5], ] const mergeStates = ({ arr1, arr2 }) => { // creating objects from the arrays: const baseObj = Object.fromEntries(arr1) const newObj = Object.fromEntries(arr2) // spreading the objects, so the latter // overwrites the former if keys match // then turning it back to an array return Object.entries({ ...baseObj, ...newObj, }) } const merged = mergeStates({ arr1: states1, arr2: states2 }) console.log(merged)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM