I have an array of subarrays in the following format:
array ( a => array ( id = 20, name = chimpanzee ) b => array ( id = 40, name = meeting ) c => array ( id = 20, name = dynasty ) d => array ( id = 50, name = chocolate ) e => array ( id = 10, name = bananas ) f => array ( id = 50, name = fantasy ) g => array ( id = 50, name = football ) )
And I would like to group it into a new array based on the id field in each subarray.
array ( 10 => array ( e => array ( id = 10, name = bananas ) ) 20 => array ( a => array ( id = 20, name = chimpanzee ) c => array ( id = 20, name = dynasty ) ) 40 => array ( b => array ( id = 40, name = meeting ) ) 50 => array ( d => array ( id = 50, name = chocolate ) f => array ( id = 50, name = fantasy ) g => array ( id = 50, name = football ) ) )
Steps to create the groupBy function, create an object as initial value for our result object. inside the array reduce, create an array for each distinct key value and push the currentValue if the key value present in the currentValue.
The group() method executes the callbackFn function once for each index of the array, returning a string (or value that can be coerced to a string) indicating the group of the element. A new property and array is created in the result object for each unique group name that is returned by the callback.
The most efficient method to group by a key on an array of objects in js is to use the reduce function. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
$arr = array(); foreach ($old_arr as $key => $item) { $arr[$item['id']][$key] = $item; } ksort($arr, SORT_NUMERIC);
foreach($array as $key => $value){ $newarray[$value['id']][$key] = $value; } var_dump($newarray);
piece of cake ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With