Collect.js flatten() Method

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', 'zambiatek'], Â Â Â Â [10, 20, 30, 40, 50] ]; Â Â Â const collection = collect(arr); Â Â Â const flatten_Val = collection.flatten(1); Â Â Â console.log(flatten_Val.all()); |
Output:
[ 'Geeks', 'GFG', 'zambiatek', 10, 20, 30, 40, 50 ]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



