Collect.js | transform() Function

The transform() function iterates over a collection and callback each item in the collection, the items inside the collection are replaced by the new callback values. It is similar to the JavaScript map() function but the values got replaced in transform() function.
In JavaScript, the array is first converted to a collection and then the function is applied to the collection.

Syntax:

data.transform(item, key)

Parameters: This function accepts two parameter as mentioned above and described below:

  • item: This parameter holds the collection item.
  • key: This parameter holds new operational value.

Return Value: Returns an modified array which is created by this function.

Below examples illustrate the transform() function in collect.js



Example 1: Here in this example, we take a collection and then using the transform() function modified the values using the key transformation parameter and return the new value.

filter_none

edit
close

play_arrow

link
brightness_4
code

// It is used to import collect.js library
const collect = require('collect.js');
  
const data= collect([1, 2, 3, 4, 5]);
  
data.transform((item, key) => item * 5);
  
console.log(data.all());

chevron_right


Output:

[5 , 10 , 15 , 20 , 25 ]

Example 2: Same thing we have done here as above example.

filter_none

edit
close

play_arrow

link
brightness_4
code

// It is used to import collect.js library
const collect = require('collect.js');
  
const x= collect([10, 20, 30, 40, 50]);
  
x.transform((item, key) => item / 10);
  
console.log(x.all());

chevron_right


Output:

[1 , 2 , 3 , 4 , 5 ]

Reference: https://collect.js.org/api/transform.html

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : akhilsharma870

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.