Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using an Array.map as a foreach good practice? [closed]

I'm already using an Array.map, but with the same data, I need to do some other calculations. Should I do those calculations within the map or do it in a for each after the map?

    return res.data.map(function (obj) {
        if(obj.status.id == 6 || obj.status.id == 5){
            dateDifference(obj.created_at,obj.closed_at);
        }else{
            $scope.open++;
        }
        return {
            "id":obj.id,
            "subject": obj.subject,
            "requester": obj.requester.name,
            "assigned": obj.assigned ? obj.assigned.name : '',
            "priority": obj.priority.name,
            "status": obj.status.name,
            "category": obj.category.name,
            "created_at": moment(obj.created_at).utcOffset("06:00").format('lll'),
            "updated_at": moment(obj.updated_at).utcOffset("06:00").format('lll')
        }
     })
like image 950
Jason Spick Avatar asked May 17 '26 23:05

Jason Spick


1 Answers

I don't see it as a 'good practice', but I don't see it as a bad practice either. Fact is, .map() is designed to both iterate and create a new resulting array.

Perhaps the answer lies in its definition.

From the JS website :

"The map() method creates a new array with the results of calling a provided function on every element in this array."

From the PHP website (for fun) :

"array_map() returns an array containing all the elements of array1 after applying the callback function to each one."

Nothing keeps you from doing what you want in that callback function.

If you, personnally, are not comfortable doing that, you could achieve the same thing doing a 'for each' while building your own new array. Which is probably what I would do in your specific case. I'd rather do that than have to iterate 2 times over my array.

Though, as Bergi mentionned, it is a better practice to iterate twice over the array if it makes sense sematically.

If performance were to become an issue (iterating twice on a long array). Here is what I would be inclined to do :

for (var i=0; i<myArray.length; i++) {
    doStuffA(myArray[i]);
    doStuffB(myArray[i]);
}

which is quite clear semantically. Instead of iterating twice.

Of course, some pleople might (will probably) disagree with me.

like image 175
phenxd Avatar answered May 20 '26 12:05

phenxd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!