Skip to content
Related Articles

Related Articles

Improve Article

Collect.js flatten() Method

  • Last Updated : 25 Nov, 2020
Geek Week

Collect.js is a wrapper library for working with arrays and objects which is dependency-free and easy to use. The flatten() method is used to flatten a multi-dimensional collection into a single dimensional collection and returns the flatten single dimensional collection elements.

Syntax:

collect(array).flatten()

Parameters: The collect() method takes one argument that is converted into the collection and then flatten() method is applied on it.

Return Value: This method returns the flatten single dimensional collection elements.

Example 1: Below example illustrates the flatten() method in collect.js



HTML




const collect = require('collect.js');
  
let obj = [
    {
        name: 'Rahul',
        score: 98,
    },
    {
        name: 'Aditya',
        score: 96,
    },
    {
        name: 'Abhishek',
        score: 80
    }
];
   
const collection = collect(obj); 
const flatten_Val = collection.flatten(1); 
console.log(flatten_Val.all());

Output:

[ 'Rahul', 98, 'Aditya', 96, 'Abhishek', 80 ]

Example 2:

html




const collect = require('collect.js');
   
let arr = [
    ['Geeks', 'GFG', 'GeeksforGeeks'],
    [10, 20, 30, 40, 50]
];
   
const collection = collect(arr);
   
const flatten_Val = collection.flatten(1);
   
console.log(flatten_Val.all());

Output:

[ 'Geeks', 'GFG', 'GeeksforGeeks', 10, 20, 30, 40, 50 ]

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 :