gpt4 book ai didi

Javascript 将数组对生成键索引列表

转载 作者:行者123 更新时间:2023-11-30 09:18:19 24 4
gpt4 key购买 nike

enter image description here

我有如下所示的数组对列表:

0: [0, "535222325"]
1: [1, "346362534"]
2: [0, "534534646"]
3: [1, "745354367"]
^ <--- Index for array where to append value

我如何通过索引键的第一个值将其转换为如下所示的列表

0: ["535222325","534534646"]
1: ["346362534","745354367"]
^ <--- Unique index found from array above

或者当在for循环中找到具有匹配索引的值时如何追加到键中

我的脚本示例:

for(var u = 0; u < Object.keys(freshData).length; u++) {
tag[u].Index <-- This I want to use as a key, whenever new unique match appears
tag[u].Value <-- This I want to add in to array of that key
}

对于非常糟糕的解释,我们深表歉意。 Target 只是通过唯一键创建列表,这些键在 for 循环中找到。

最佳答案

Array.prototype.reduce 拯救:

const data = [
[0, "535222325"],
[1, "346362534"],
[0, "534534646"],
[1, "745354367"]
]

const groupKVPairs = (pairs, container = {}) => pairs.reduce(
(acc, [key, value]) => {
const group = acc[key]
if (group !== undefined) group.push(value)
else acc[key] = [value]
return acc
},
container
)

console.log(groupKVPairs(data, []))
// output -> [["535222325", "534534646"], ["346362534", "745354367"]]

console.log(groupKVPairs(data, {}))
// output -> { "0": ["535222325", "534534646"], "1": ["346362534", "745354367"]}

console.log(groupKVPairs(data))
// output -> { "0": ["535222325", "534534646"], "1": ["346362534", "745354367"]}

关于Javascript 将数组对生成键索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com