Google News
logo
Collect.js - Interview Questions
What is each() and eachSpread() methods in Collect.js?
each() : The each() method iterates over the items in the collection and passes each item to a callback:
let sum = 0;

const collection = collect([1, 3, 3, 7]);

collection.each((item) => {
  sum += item;
});

// console.log(sum);
// 14
If you would like to stop iterating through the items, you may return false from your callback:
let sum = 0;

const collection = collect([1, 3, 3, 7]);

collection.each((item) => {
  sum += item;

  if (sum > 5) {
    return false;
  }
});

// console.log(sum);
// 7
eachSpread()The eachSpread() method iterates over the collection's items, passing each nested item value into the given callback:
const collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

collection.eachSpread((name, age) => {
  //
});

You may stop iterating through the items by returning false from the callback:

collection.eachSpread((name, age) => false);
Advertisement