const test = [{a:1},{b:2},{c:3},{d:4},{a:5},{b:6},{c:7},{a:8},{c:9}]
Need output like below,
On repeat of key "a", need to create new array till the same key repeat
[{a:1},{b:2},{c:3},{d:4}]
[{a:5},{b:6},{c:7}]
[{a:8},{c:9}]
const test = [{a:1},{b:2},{c:3},{d:4},{a:5},{b:6},{c:7},{a:8},{c:9}]
Need output like below,
On repeat of key "a", need to create new array till the same key repeat
[{a:1},{b:2},{c:3},{d:4}]
[{a:5},{b:6},{c:7}]
[{a:8},{c:9}]
4
Answers
You can try some thing like below.
You can achieve this with
reduce
function.Here,
reduce
function is used to iterate through the test array and accumulate elements into subarrays. Whenever an object with the key"a"
is encountered, a new empty subarray is added to the result. Elements are then pushed into the most recent subarray.Finally, the resulting subarrays are filtered to remove any empty ones, and the output will contain the desired grouped arrays.
Example using Array.prototype.reduceRight(), Array.prototype.unshift() and Array.prototype.splice()
the
test
array if first shallow cloned using the Array Spread syntax[...test]
and later referenced asref
. On every reduceRight iteration, if theob["a"] &&
matches we append to the accumulator Arrayacc
the contents of theref
clone from indexi
to the end. Splice modifies theref
array making it smaller and smaller. So basically what it does is: takes fromref
chunks of array data and inserts them intoacc
– returning it.And there you have the 2D (nested)
result
Array:For the best performance don’t mutate the source and don’t push by 1 element, rather slice:
And a benchmark: