gpt4 book ai didi

javascript - make 函数从作为参数传入的数组中获取多个变量

转载 作者:行者123 更新时间:2023-12-01 02:00:54 26 4
gpt4 key购买 nike

如何使函数从作为参数传入的数组中获取多个变量?

Edited

例如:

实现这一目标:

const inputObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
]
// expected output:
const outputObj = [
[ 'Anna', 10, 'Monday' ],
[ 'Anna', 19, 'Wednesday' ],
[ 'Beatrice', 29, 'Monday' ],
[ 'Beatrice', 11, 'Wednesday' ]
]

const arr = [0, 2]

const someFunction = (obj, v, a) => {
const result = obj.reduce((acc, cur) => {
const key = `${cur[a[0]]}|${cur[a[1]]}`
if(!acc[key]) acc[key] = cur
else acc[key][1] += cur[v]
return acc
}, {})
return Object.values(result)
}


console.log(someFunction(inputObj, 1, arr))

这样:

const arr = [0, 2, 3, ...] // basically the array could contain any number of items.

const someFunction = (obj, v, objParams) => {
const result = obj.reduce((acc, cur) => {
const key = ???
...
}, {})
}

为了使该函数可以重用并接受自定义大小的数组,请检查数组中的列号是否相同,然后将传入的列的总和作为 v

如何从 objParams 声明变量以获得与上面代码相​​同的结果?

另外如何在cur中间添加v

最佳答案

假设 objParams 是一个未知大小的数组(本例中为字符串):

const objParams = ["c1", "c2", "c3"];
const key = objParams.join(']}|${cur[');
const built = '${cur[' + key + ']';

构建是:

${cur[c1]}|${cur[c2]}|${cur[c3]

关于javascript - make 函数从作为参数传入的数组中获取多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594713/

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