How to reposition the elements of a json array conditionally using jq?
2
votes
1
answer
1636
views
I want to re-position elements of an array (change index of array elements) based on a condition. I don't know how to translate this to jq which is more of a *functional* language.
Basically I want to sort the array but the *relative* position of specific elements should be unchanged.
for each element:
if element.role==master => record type
for each element:
if element.type == recorded type
reposition the element to be below its master of similar type
I can explain better with an example. Consider input.json
. How can I move all non-master elements with type "x" below their masters **without** changing the **relative** position of non-master of the same type. (ignore "num" parameter. Used only for showing relativity)
input.json
[
{
"type": "A",
"role": "master"
},
{
"num": 1,
"type": "A"
},
{
"type": "C",
"role": "master"
},
{
"num": 4,
"type": "B"
},
{
"num": 2,
"type": "B"
},
{
"type": "B",
"role": "master"
},
{
"num": 3,
"type": "B"
},
{
"num": 4,
"type": "A"
},
{
"num": 2,
"type": "A"
},
{
"num": 0,
"type": "C"
},
{
"num": 5,
"type": "C"
},
{
"num": 1,
"type": "A"
},
{
"num": 1,
"type": "B"
}
]
goal.json
[
{
"type": "A",
"role": "master"
},
{
"num": 1,
"type": "A"
},
{
"num": 4,
"type": "A"
},
{
"num": 2,
"type": "A"
},
{
"num": 1,
"type": "A"
},
{
"type": "C",
"role": "master"
},
{
"num": 0,
"type": "C"
},
{
"num": 5,
"type": "C"
},
{
"type": "B",
"role": "master"
},
{
"num": 4,
"type": "B"
},
{
"num": 2,
"type": "B"
},
{
"num": 3,
"type": "B"
},
{
"num": 1,
"type": "B"
}
]
As you can see:
1- The relative positions of masters is left unchanged (A - C - B)
2- The relative positions of non-masters of the same type is left unchanged.
(I guess this problem has a name in algorithms literature? in-place sorting?)
Asked by Zeta.Investigator
(1190 rep)
Jul 9, 2021, 09:26 PM
Last activity: Jul 9, 2021, 11:50 PM
Last activity: Jul 9, 2021, 11:50 PM