Google News
logo
Collect.js - Interview Questions
Explain map methods in Collect.js.
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',
// }
Advertisement