有如下一个数组
[
{"id": 100006, "value": "40,1666"},
{"id": 100017, "value": "112,113"},
]
期望输出如下结果
['10006:40,100017:112',
'10006:40,100017:113',
'10006:1666,100017:112',
'10006:1666,100017:113',
]
亦或者输入三个或者N个数组
[
{"id": 100006, "value": "40,1666"},
{"id": 100017, "value": "112,113"},
{"id": 100018, "value": "1,2"},
]
能够输出
['10006:40,100017:112',
'10006:40,100017:113',
'10006:40,100018:1',
'10006:40,100018:2',
'10006:1666,100017:112',
'10006:1666,100017:113',
'10006:1666,100018:1',
'10006:1666,100018:2',
'100017:112,100018:1',
'100017:112,100018:2',
'100017:113,100018:1',
'100017:113,100018:2',
]
請問怎麼實作這個函數?
附加:最好不論輸入數組長度都能正確的輸出對應的值(是所有數組的里的值都會被匹配一次),有些答案是固定取值0,1的,期望不要這樣。
淡淡烟草味2017-06-28 09:28:45
試了一下仿「純函數式」的程式碼:
兩兩相配(這是答主想要的效果):
function transform(list) {
return list.map(i =>
i.value
.split(',')
.map(j => `${i.id}:${j}`)
).reduce((acc, current, i, arr) => {
current.forEach(L => {
arr
.filter((_, k) => k > i)
.forEach(j => {
j.forEach(R => {
acc.push(`${L},${R}`)
})
})
})
return acc
}, [])
}
另外,附加上NN相符:
function transform(list) {
return list.map(i =>
i.value
.split(',')
.map(j => `${i.id}:${j}`)
).reduce((l, r) => (
l.length === 0 ?
r :
l.map(g =>
r.map(j =>
`${g},${j}`
)
)
.reduce((l, r) =>
l.concat(r), []
)
), [])
}