Google News
logo
Collect.js Interview Questions
join() : The join() method joins the collection's values with a string:
collect(['a', 'b', 'c']).join(', ');
// 'a, b, c'

collect(['a', 'b', 'c']).join(', ', ', and ');
// 'a, b, and c'

collect(['a', 'b']).join(', ', ' and ');
// 'a and b'

collect(['a']).join(', ', ' and ');
// 'a'

collect([]).join(', ', ' and ');
// ''
keyBy() : The keyBy() method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:
const collection = collect([
  {
    product: 'Chair',
    manufacturer: 'IKEA',
  },
  {
    product: 'Desk',
    manufacturer: 'IKEA',
  },
  {
    product: 'Chair',
    manufacturer: 'Herman Miller',
  },
]);

const keyed = collection.keyBy('manufacturer');

keyed.all();

// {
//   IKEA: {
//     product: 'Desk',
//     manufacturer: 'IKEA',
//   },
//   'Herman Miller': {
//     product: 'Chair',
//     manufacturer: 'Herman Miller',
//   },
// }
You may also pass a callback to the method. The callback should return the value to key the collection by:
const upperCased = collection.keyBy(item => item.manufacturer.toUpperCase());

upperCased.all();

// {
//   IKEA: {
//     product: 'Desk',
//     manufacturer: 'IKEA',
//   },
//   'HERMAN MILLER': {
//     product: 'Chair',
//     manufacturer: 'Herman Miller',
//   },
// }
keys()The keys() method returns all of the collection's keys:
const collection = collect([
  {
    club: 'Liverpool',
    nickname: 'The Reds',
  },
]);

keys = collection.keys();

// ['club', 'nickname']
last() : The last() method returns the last element in the collection that passes a given truth test:
const collection = collect([1, 2, 3]);

const last = collection.last(item => item > 1);

// 3
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:
collect([1, 2, 3, 4]).last();

// 4
macro() : The macro() method lets you register custom methods
collect().macro('uppercase', function () {
  return this.map(item => item.toUpperCase());
});

const collection = collect(['a', 'b', 'c']);

collection.uppercase();

collection.all();

// ['A', 'B', 'C']
Note that the macro method returns undefined, and therefore it is not possible to use it within a chain of methods.
 
make() : The make() method creates a new collection instance.
 
This is only added to adhere to the Laravel collection API, when using Collect.js it's recommended to use collect() directly when creating a new collection.
map() : The map() method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:
const collection = collect([1, 2, 3, 4, 5]);

const multiplied = collection.map(item => item * 2);

multiplied.all();

// [2, 4, 6, 8, 10]
Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform method.
 
mapInto() : The mapInto() method iterates through the collection and instantiates the given class with each element as a constructor:
const Player = function (name) {
  this.name = name;
};

const collection = collect([
  'Roberto Firmino',
  'Darwin Núñez',
]);

const players = collection.mapInto(Player);

players.all();

// [
//   Player { name: 'Roberto Firmino' },
//   Player { name: 'Darwin Núñez' },
// ]
mapSpread() : The mapSpread() method iterates over the collection's items, passing each nested item value into the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:
const collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

const chunks = collection.chunk(2);

const sequence = chunks.mapSpread((even, odd) => even + odd);

sequence.all();

// [1, 5, 9, 13, 17]
mapToDictionary() : Run a dictionary map over the items. The callback should return an associative array with a single key/value pair.
const collection = collect([
  { id: 1, name: 'a' },
  { id: 2, name: 'b' },
  { id: 3, name: 'c' },
  { id: 4, name: 'b' },
]);

const groups = collection.mapToDictionary(item => [item.name, item.id]);

groups.all();

// {
//   a: [1],
//   b: [2, 4],
//   c: [3],
// }
mapToGroups() : The mapToGroups() method iterates through the collection and passes each value to the given callback:
const collection = collect([
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3, name: 'C' },
  { id: 4, name: 'B' },
]);

const groups = collection.mapToGroups((item, key) => [item.name, item.id]);

// {
//   A: [1],
//   B: [2, 4],
//   C: [3],
// }
mapWithKeys() : The mapWithKeys() method iterates through the collection and passes each value to the given callback. The callback should return an array where the first element represents the key and the second element represents the value pair:
const collection = collect([
  {
    name: 'John',
    department: 'Sales',
    email: 'john@example.com',
  },
  {
    name: 'Jane',
    department: 'Marketing',
    email: 'jane@example.com',
  },
]);

const keyed = collection.mapWithKeys(item => [item.email, item.name]);

keyed.all();

// {
//   'john@example.com': 'John',
//   'jane@example.com': 'Jane',
// }
max() : The max() method returns the maximum value of a given key:
const collection = collect([
  {
    value: 10,
  },
  {
    value: -13,
  },
  {
    value: 12,
  },
  {
    unicorn: false,
  },
]);

const max = collection.max('value');

// 12
collect([-1, -2345, 12, 11, 3]).max();

// 12
merge() : The merge() method merges the given object into the original collection. If a key in the given object matches a key in the original collection, the given objects value will overwrite the value in the original collection:
const collection = collect({
  id: 1,
  price: 29,
});

const merged = collection.merge({
  price: 400,
  discount: false,
});

merged.all();

// { id: 1, price: 400, discount: false }
If our collection is an array, the values will be appended to the end of the collection:
const collection = collect(['Unicorn', 'Rainbow']);

const merged = collection.merge(['Sunshine', 'Rainbow']);

merged.all();

// ['Unicorn', 'Rainbow', 'Sunshine', 'Rainbow']
mergeRecursive() : The mergeRecursive() method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:
const collection = collect({
  product_id: 1,
  price: 100,
});

const merged = collection.mergeRecursive({
  product_id: 2,
  price: 200,
  discount: false,
});

merged.all();

// {
//   product_id: [1, 2],
//   price: [100, 200],
//   discount: false,
// }
min() : The min() method returns the minimum value of a given key:
const collection = collect([
  {
    worth: 100,
  },
  {
    worth: 900,
  },
  {
    worth: 79,
  },
]);

collection.min('worth');

// 79
collect([1, 2, 3, 4, 5]).min();

// 1
pad() : The pad() method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad PHP function.
 
To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:
const collection = collect(['A', 'B', 'C']);

let filtered = collection.pad(5, 0);

filtered.all();

// ['A', 'B', 'C', 0, 0]

filtered = collection.pad(-5, 0);

filtered.all();

// [0, 0, 'A', 'B', 'C']
 
partition() : The partition() method may be combined with destructuring to separate elements that pass a given truth test from those that do not:
const collection = collect([1, 2, 3, 4, 5, 6]);

const [underThree, overThree] = collection.partition(i => i < 3);
pull() : The pull() method removes and returns an item from the collection by its key:
const collection = collect({
  firstname: 'Michael',
  lastname: 'Cera',
});

collection.pull('lastname');

// Cera

collection.all();

// { firstname: 'Michael' }
push() : The push() method appends an item to the end of the collection:
const collection = collect([1, 2, 3, 4]);

collection.push(5);

collection.all();

// [1, 2, 3, 4, 5]
put() : The put() method sets the given key and value in the collection:
const collection = collect(['JavaScript', 'Python']);

collection.put('Ruby');

collection.all();

// ['JavaScript', 'Python', 'Ruby']
random() : The random() method returns a random item from the collection:
const collection = collect([1, 2, 3, 4, 5]);

collection.random();

// 4 (retrieved randomly)
You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:
const threeRandom = collection.random(3);

// Collection { items: [ 5, 3, 4 ] } (retrieved randomly)

const oneRandom = collection.random(1);

// Collection { items: [ 3 ] } (retrieved randomly)

oneRandom.all();

// [3]
reduce()The reduce() method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:
const collection = collect([1, 2, 3]);

const total = collection.reduce((carry, item) => carry + item);

// 6
The value for carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

const total = collection.reduce((carry, item) => carry + item, 4);

// 10

Sources : Collect.js, more,.