Collect.js | collapse() Method

Collect.js is a fluent and convenient wrapper for working with arrays and objects. The JavaScript array is first transformed into a collection and then the function is applied to the collection.

The collapse() method convert collection of arrays into a single flat array.

Installation:

  • Collect.js can be installed via NPM:
    npm install --save collect.js
  • You can also use CDN of collect.js
    <script src="https://cdnjs.com/libraries/collect.js"></script>

Syntax:

collect(array).collapse()

Parameters: The collect() takes one argument that is converted into the collection and then collapse() function is applied on it, which will convert into a single flat array.



Return Value: Returns an array.

Below examples illustrate the collapse() method in JavaScript:

Example 1: Here collect = require(‘collect.js’) is used to import the collect.js library into the file.

filter_none

edit
close

play_arrow

link
brightness_4
code

const collect = require('collect.js');
  
let arr = [1, [1, 2], [{}, 3]]
  
// convert array into collection
const collection = collect(arr);
  
// collapsing the array into single array
const collapased = collection.collapse();
  
// returning the array with all() method.
let singleArray =   collapased.all();
  
console.log("Single array: ", singleArray);

chevron_right


Output

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

const collect = require('collect.js');
  
let arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
  
// convert array into collection
const collection = collect(arr);
  
// collapsing the array into single array
const collapased = collection.collapse();
  
// returning the array with all() method.
let singleArray =   collapased.all();
  
console.log("Single array: ", singleArray);
  

chevron_right


Output

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 : Akanksha_Rai

Article Tags :

Be the First to upvote.


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