Lodash _.reduce Method Example

_.reduce is a little bit like a filter function. The only difference is that you can choose the form of the returned object.

Learn Lodash JS at Lodash JS Tutorial with Examples.

Lodash _.reduce Method Example

<!DOCTYPE html>
<html>
<head>
    <title>Lodash Tutorial</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

    <script type="text/javascript">
  var users = [
   { name: "John", age: 30 },
   { name: "Jane", age: 28 },
   { name: "Bill", age: 65 },
   { name: "Emily", age: 17 },
   { name: "Jack", age: 30 }
  ]

  var reducedUsers = _.reduce(users, function (result, user) {
   if(user.age >= 18 && user.age <= 59) {
    (result[user.age] || (result[user.age] = [])).push(user);
   }
    
   return result;
  }, {});
  
  console.log(JSON.stringify(reducedUsers));
    </script>
</head>
<body></body>
</html>
The above HTML prints below output on the console:
{"28":[{"name":"Jane","age":28}],"30":[{"name":"John","age":30},{"name":"Jack","age":30}]}

Reference


Comments