In JQ, I would like to duplicate elements n-times in the first array based on the values of the second array. As seen in the example below I would like to have the first element of the first array two times and the second element of the array three times. The number of elements are different in each case.
[["1/optimized/17853791_fpx.tif", "3/optimized/17853793_fpx.tif"],
["2", "3"]]
The desired output should look like:
["1/optimized/17853791_fpx.tif", "1/optimized/17853791_fpx.tif", "3/optimized/17853793_fpx.tif", "3/optimized/17853793_fpx.tif", "3/optimized/17853793_fpx.tif"]
I tried out some things but couldn't figure it out..
CodePudding user response:
A transpose-free solution:
[. as [$x, $n]
| range(0;$n|length) as $i
| range(0;$n[$i]|tonumber)|$x[$i]]
CodePudding user response:
Here's a solution using transpose
, limit
and repeat
:
jq 'transpose | map(limit(last | tonumber; repeat(first)))' file.json
[
"1/optimized/17853791_fpx.tif",
"1/optimized/17853791_fpx.tif",
"3/optimized/17853793_fpx.tif",
"3/optimized/17853793_fpx.tif",
"3/optimized/17853793_fpx.tif"
]
CodePudding user response:
def r($in;n): range(0;n)|$in;
.[1] |= map(tonumber)
| transpose
| map(r(first;last))