I am trying to write a function that will convert an array that starts with ‘and’ | ‘or’ then process the next elements in the same level until the next ‘and’ | ‘or’. It will be more clear in the following example:
// from
[
'and',
1,
2,
'or',
3,
4,
],
// to
{ and: [
1,
2,
{
or: [
3,
4
]
}
]
}
any thoughts?
3
Answers
This can be achieved with the recursive function just like below:
This method should be called like below
You can define a helper function and use
reduce
:Use
Array.reduceRight()
with a default value of an empty array. Reducing from the right means iterating from the last item to the first.If the item is a string, create a new object wrapped in array, with the item as a key, and the current accumulator (
acc
) as the value. If not prepend the item to the current accumulator array:If you need a more granular approach (ie – some items may be strings), identify the "and" and "or" values: