Anahkiasen / underscore-php

A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
http://anahkiasen.github.com/underscore-php/
1.12k stars 88 forks source link

Reduce function on Arrays ? #25

Closed alxscms closed 9 years ago

alxscms commented 10 years ago

Hi, I am facing a problem, I have an array of arrays, and I want each of those arrays merged together. For example the array [[1, 2], [3], [4, 5, 6]] would become the array [1, 2, 3, 4, 5, 6].

I know how to do it with the underscore.js library (with the reduce function http://underscorejs.org/#reduce), but I can't find a way to do it with underscore.php. Does anyone have any clue ? Is it a missing functionality ?

Thanks

black-snow commented 10 years ago

Couldn't find a reduce neither.

Anahkiasen commented 10 years ago

It's not in the code but it should work, calling Arrays::reduce should simply defer to http://www.php.net/manual/en/function.array-reduce.php

black-snow commented 10 years ago

Correct. Dispatch::toNative() dispatches Arrays::reduce() correctly.

Simple example:

<?php

require 'vendor/autoload.php';

$ar = [[1, 2], [3], [4, 5, 6]];

var_dump(\Underscore\Types\Arrays::reduce($ar, function($carry, $item){
    if(is_array($item))
        foreach ($item as $i)
            $carry[] = $i;
    else
        $carry[] = $item;
    return $carry;
}, array()));

$a = new \Underscore\Types\Arrays($ar);

var_dump($a->reduce(function($carry, $item){
        if(is_array($item))
            foreach ($item as $i)
                $carry[] = $i;
        else
            $carry[] = $item;
        return $carry;
    }, array())
->obtain());