Skip to content
Related Articles

Related Articles

Improve Article

Collect.js | collapse() Method

  • Last Updated : 30 Jun, 2020
Geek Week

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.




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);

Output

Example 2:




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);
  

Output

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :