Different ways to leverage the countBy and filter functions in lodash

Here is a data array that I am working with:

const data = [
  { year: 1900, title: 'test 1' },
  { year: 2000, title: 'test 2' },
  { year: 2000, title: 'test 3' },
  { year: 2000, title: 'test 4' },
];

My goal is to create an array of years where each year appears more than twice:

[2000]

We can easily achieve the countBy using the following code:

_.chain(data)
.countBy('year')
.value()

This will give us the following object:

{'1900': 1, '2000': 3}

I am facing some challenges with the filtering part. When I tried the following code, it returned an empty array:

_.chain(data)
  .countBy('year')
  .filter((o) => {
    o > 2;
  })
  .value();

Can someone guide me on the correct approach?

Answer №1

Swap out _.filter() for _.pick() since filter will only return the values ([3]), not the keys (the years). Make sure to also include a callback function - o => o > 2. Then, extract an array of the keys (years), and convert them to numbers if necessary.

const data = [{"year":1900,"title":"test 1"},{"year":2000,"title":"test 2"},{"year":2000,"title":"test 3"},{"year":2000,"title":"test 4"}];

const result = _(data)
  .countBy('year')
  .pickBy(o => o > 2)
  .keys()
  .map(Number) // <- if you want the years as numbers
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Answer №2

const newData = [
  { century: 1800, name: 'example 1' },
  { century: 1900, name: 'example 2' },
  { century: 2000, name: 'example 3' },
  { century: 2000, name: 'example 4' },
];

const centuryNamesMap = _.groupBy(newData, 'century');
const centuriesWithMoreThanTwoEntries = _.filter(_.keys(centuryNamesMap), century => centuryNamesMap[century].length > 2);

console.log(centuriesWithMoreThanTwoEntries);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve property value from a component in Vue.js 2.0

I am currently working with a specific component that allows for date selection: <template> <div class="animated fadeIn"> <div class="col-sm-6 col-lg-6"> <datepicker class="form-control" :value="config.state.fromDate" ...

Encountered an issue when trying to convert JSON into an array and loop through it in an HTML file using a

Currently, I am working on a project involving Angular where I am retrieving data from an API through a GET call. Specifically, one column's data is being converted from JSON to an array. However, when attempting to iterate over this array in the HTML ...

cracking reCAPTCHA without needing to click a button or submit a form (utilizing callback functions)

Currently, I am facing a challenge with solving a reCaptcha on a specific website that I am trying to extract data from. Typically, the process involves locating the captcha inside a form, sending the captcha data to a captcha-solving API (I'm using ...

Utilize a method of an object as the callback function for an AJAX request

I am dealing with a javascript Object named Company, which I need to instantiate multiple times. Each instance of Company should independently handle its own server communication through ajax calls, all contained within the class. My current setup is as ...

When removing a specific option from a dropdown menu, the default selection is chosen instead of the

So I have a select element that initially had multiple options selected. After I manipulated it with my code, only one option remains selected, but because I removed the previous selections, the default option is now being shown instead of the next selecte ...

The next function is not defined error in the controller function

Everything was running smoothly until I suddenly encountered this error message: ReferenceError: next is not defined. I'm puzzled because I didn't make any changes to this function. const Users = require('../data/users.model') exports ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

"An issue with the external jQuery file loop causes it to skip either the first or

I have a webpage where I am dynamically loading content from an external JavaScript file. This file identifies div elements with a specific class name and then fills the content of those divs based on a custom attribute, which contains a link to an API. Th ...

Struggling to reach global variables in AngularJS?

Based on the inquiry found in this source: Global variables in AngularJS It has been suggested that global variables can be set using a service or rootscope. My issue lies in the fact that I am unable to access the global variable within a function, unle ...

Accessing Promise.all in the rejection function is not allowed

I have a service that retrieves data, and I make 5 calls to it with different parameters to retrieve various datasets. When the function is successful, everything works fine. However, in case of failure for any of the 5 calls, I need to handle it differen ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

Guide on utilizing Json.net for extracting an array from a json document

After conducting thorough research, I have come across several solutions to similar problems like mine. Unfortunately, none of them have proven to be successful so far. My main goal is to parse a json file where the first item is an array structured like t ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...

Exploring the JsonArray Response entity

Trying to decode my fetch response: fetch('restservices/users/', fetchOptions) .then(function (response) { if (response.ok) { console.log('1'); console.log(response) const responseSjon = response.json ...

A camera control stick in JavaScript

Looking to develop a camera control joystick that can move in four directions: left, right, up, and down with the ability to stop. After extensive research online, I stumbled upon something called nipplejs and attached the code below: var radius = 100; ...

Avoid prompting unsaved changes notification when running OnSelectedIndexChanged event for a drop-down list

Incorporating this jQuery code to detect unsaved modifications and notify users before they navigate away has been really helpful. var _changesMade = false; $(document).ready(function () { $('form').bind($.browser.msie ? 'p ...

What is the best way to integrate React Portal with React Hook?

There is a specific requirement to listen to a custom event in the browser and then have a button that triggers the opening of a popup window. Currently, React Portal is being used to open this secondary window (PopupWindow). However, when hooks are used i ...

What is the reason that the Mongoose updateMany() function only functions properly when combined with .then

Currently delving into the intricacies of Mongoose, I am perplexed as to why updateMany() requires a .then() at the end in order to be executed. For instance, here is the snippet that I'm endeavoring to execute, with the intention of altering the rat ...

How can we use JavaScript to convert base 10 colors or hex colors to ANSI colors?

I am searching for a method to convert base 10 colors or hex colors into ANSI colors that are compatible with the terminal. For instance, \u001b[31m represents red in ANSI colors. Any suggestions on how this can be achieved using JavaScript code or a ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...