how to use the select function from the underscore library in javascript

To use the select function from underscore.js in JavaScript, follow these steps:

  1. First, include the underscore.js library in your project by adding a script tag to your HTML file:
<script src="underscore.js"></script>
38 chars
2 lines
  1. Then, define an array of objects that you want to filter:
index.tsx
const users = [
  {name: 'John', age: 25},
  {name: 'Sarah', age: 32},
  {name: 'Adam', age: 18},
  {name: 'Ava', age: 22},
];
127 chars
7 lines
  1. Finally, use the select function to filter the array based on a predicate. The predicate is a function that returns true or false for each element of the array. In this example, we will select all users who are over 21 years old:
index.tsx
const adults = _.select(users, function(user) {
  return user.age > 21;
});

console.log(adults);
// Output: [{name: 'Sarah', age: 32}, {name: 'Ava', age: 22}]
160 chars
7 lines
  1. Alternatively, you can use the filter method instead of select, as they do the same thing:
index.tsx
const adults = _.filter(users, function(user) {
  return user.age > 21;
});

console.log(adults);
// Output: [{name: 'Sarah', age: 32}, {name: 'Ava', age: 22}]
160 chars
7 lines

gistlibby LogSnag