For loop vs Each vs Reduce vs Filter vs Map

Edit on GitHub

Setup

const members = [
  { role_id: 1 },
  { role_id: 1 },
  { role_id: 2 },
  { role_id: 1 },
  { role_id: 1 },
  { role_id: 2 },
  { role_id: 1 },
  { role_id: 1 },
  { role_id: 1 },
  { role_id: 1 }
];

Tests

  • For loop

    let count = 0;
    for (let i = 0; i < members.length; i += 1) {
      if (members[i].role_id === 1) {
        count = count + 1
      }
    }
  • Each

    let count = 0;
    members.forEach(function (member) {
      if (member.role_id === 1) {
        count = count + 1
      }
    });
  • Reduce

    const count = members.reduce(function (result, member) {
      if (member.role_id === 1) {
        return result + 1;
      } else {
        return result;
      }
    }, 0);
  • Filter

    const count = members.filter(function (member) {
      return member.role_id === 1
    }).length;
  • Map

    let count = 0;
    members.map(function (member) {
      if (member.role_id === 1) {
        count = count + 1
      }
    });