Using .map to solve logical code challenges

Using .map to solve logical code

On several occasions, you tend to loop through a collection of objects or arrays, and for each of the items in the array, you want to do something special with it, maybe you only need to add and extra key-value or check if a particular value matches a certain test. More than often, we over exaggerate what the .each method is capable of and tend to use it in solving problems it cannot let’s look at an example below:

use .map when coding with the Laravel and array_map when writing core php.

[ { id: 1, name: ”hello1′, newkey: value }, { id: 2, name: ”hello2′, newkey: value }, { id: 3, name: ”hello3′, newkey: value }, ]

You first try may be this

 $collection->each(function ($item){
   $item->push(['newkey'=> $item->countOne + $item->countTwo]);
});

Unfortunately, that dint work, and why because the each method loops over the items, but doesn’t return the value. You need to use map instead here so lets look at a working solution in this article of Using .map to solve logical code challenges

Use Case One: Add key value to the current object in the eloquent collection

$collection = $collection->map(function ($item) {
    $item->newkey = $item->countOne + $item->countTwo;

    return $item;
});

Note that map creates a new collection, so you need to assign it to a variable as well.

Documentation: https://laravel.com/docs/7.x/collections#method-map

The solution above is a perfect fix but you can also use transform to mutate it directly

 $collection->transform(function ($item){
            $item->newkey = $item->countOne + $item->countTwo;
              return $item;
        });

Use Case Two: For the following example, we will transform each item in the collection and return a new collection

use Illuminate\Support\Collection;
// Create a new collection

$collection = new Collection([
    'jhon', 'tom', 'mike', 'stuart'
]);

// Change all items to uppercase and create a new collection of them
$names = $collection->map(function($item, $key) {
   return strtoupper($item);
});

The $names variable will be an instance of Collection class and contain a value similar to following:

Collection {#510 ▼
  #items: array:4 [▼
    0 => "JHON"
    1 => "TOM"
    2 => "MIKE"
    3 => "STUART"
  ]
}

If you dump the original collection $collection, you will find it will remain unchanged.

See Also:

Basic things a programmer should know

Be the first to comment

Leave a Reply