Determine the frequency of a specific string within an array by utilizing Lodash

I have retrieved an array of tags for blog posts from a database.

Here is an example of the query result:

["apple","banana", "apple", "orange","grapes","mango","banana"];

I am looking to determine how many times each string is repeated within the array in order to create a tag cloud.

The desired final output would be:

[{name:"apple",count:2}, {name:"banana", count:2}, {name: "orange",count:1} ...];

In my project, I am utilizing lodash and prefer to use it if possible. However, plain JavaScript is also acceptable.

Answer №1

If you're looking to streamline your data processing, consider leveraging the power of groupBy along with map for custom formatting:

const items = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

const formattedData = _.values(_.groupBy(items)).map(item => ({name: item[0], quantity: item.length}));

console.log(formattedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №2

Implement a solution using the reduce and map methods

var words = ["apple","banana", "apple", "orange","grapes","mango","banana"];

var wordMap = words.reduce((acc, curr) => ( acc[curr] = acc[curr] || 0, acc[curr]++, acc ), {});

var result = Object.keys(wordMap).map( key => ({name: key, count:wordMap[key]}) );

See Code Demo Below

var input = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

var map = input.reduce((a, c) => (a[c] = a[c] || 0, a[c]++, a), {});

var output = Object.keys(map).map(s => ({
  name: s,
  count: map[s]
}));

console.log(output);

Answer №3

Generate a chart that links names to quantities. Cycle through the collection, checking each element; if it already exists in the chart, increase its quantity by one, otherwise set its quantity to one.

if (label in chart) { chart[label] += 1 }
else { chart[label] = 1 }

Next, iterate through the chart and transform it into an array of elements.

Answer №4

If you want to tally up items, you can utilize the _.countBy() function from Lodash. Afterwards, transform the data into the desired format by using _.entries(), and then map the pairs into objects:

const data = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

const result = _.entries(_.countBy(data)).map(([name, count]) => ({ name, count }));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></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

The most efficient method for manipulating the DOM in React for superior performance

When it comes to animating a DOM element with a number sequence going from 0 to N using a tween library in React, what is the most efficient and reliable approach? Would using setState be considered ideal, even when combined with the shouldComponentUpdate ...

Display issue with loading animation

After clicking the button and seeing the alert message, I noticed that the loading animation does not display during the await new Promise(r => setTimeout(r, 2000));. /* script.js */ async function refreshStatus() { document.getElementById("load ...

Eliminate redundant sets of comma-separated numbers from the jQuery input text value

On my webpage, there is an input with a value that looks like this: 1,7,1,4,22,58,58,1,1,4,7 <input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false"> I have attempted mu ...

JavaScript prohibiting input prior to execution

Having trouble with executing this javascript before the user input, can anyone assist me in resolving this issue. I just want to create a simple html page with a textbox and a button. When the button is clicked, it should open a new window with a modifie ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Trying to retrieve a CSS property using jQuery

Having trouble retrieving the correct CSS value for a background using a spectrum.js color picker. No matter which color is chosen, rgba(0,0,0,0) is always selected. Strangely enough, when checking the background in the console, it shows up correctly in th ...

Question: Which is preferable, std::tuples or std::array?

I've always believed that std::tuple was a bit extravagant, not really efficient. However, my understanding has changed as I have learned that tuples offer contiguous memory due to the object layout rules. I am aware that tuples are generated through ...

What could be causing the discrepancy between the labels below the chart and the labels in the legend on the bar chart in Chart.js?

I'm looking to create a chart with labels on the xAxes and the same labels in the legend. I've tried various solutions, but so far, the best result I've achieved is shown in the code snippet below. However, all bars seem to be connected to m ...

Unending cycle in React with a custom hook

After attempting to create a method using a custom react hook to streamline state logic across multiple components, I encountered an invariant violation labeled "prevent infinite loop". function useCounter(initial) { const [count, setCounter] = useState ...

Remove a struct from an array of structs if the string element within the struct is missing or blank in Swift

Imagine having a struct that looks like this: struct Model: Codable { var myVariable: String var myVariable2: String? } Sometimes, the value of myVariable2 can be nil or an empty string "". How can I effectively filter out the structs with emp ...

The regex pattern is failing to match the input pattern

<input type="text" id="url" name="url" pattern="/ ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)(amazon)|(flipkart)+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$ /" ...

JavaScript function to validate percentages

I am looking to create a function that will determine whether a given value is a percentage. The function should return true for numbers followed by a '%' symbol or decimal values representing percentages. Here's how I want it to work: /* ...

Using the "this" keyword to set a timer in a JavaScript class with setTimeout()

Implementing setTimeout() inside a class function in JavaScript is my current goal. The purpose of setTimeout() is to trigger another method within the same Class, so I have written the function as window.setTimeout("this.anotherMethod", 4000). However, th ...

Searching for a table element and clicking it based on its text with Protractor

<tr id="item" ng-repeat="item in itemList> <td id="code" ng-repeat="column in columns">Different Text</td> </tr> I have encountered some similar issues before, but I am still struggling to find a solution. Here is what I have at ...

Issue with Vuetify v-alert not appearing after updating reactive property

I am trying to set up a conditional rendering for a v-alert if the login response code is 401 Unauthorized. Here is how I have defined the alert: <v-alert v-if="this.show" type="error">Invalid email and/or password.</v-alert> Within the data ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

Learn the technique for creating smooth background fade effects in three.js

As I dive into learning three.js, I am faced with a challenge. I have implemented three buttons for different backgrounds in my project, but I want them to fade in and out when clicked. The code snippet I am currently using for the buttons is given below: ...

How to pass command line arguments into Chrome using WebDriverIO Selenium from the config.js file

Is there a way to add the disable-web-security flag for Chrome in order to conduct UI tests? How can I incorporate commands into the wdio.config file () to achieve this? capabilities: [{ browserName: 'chrome' }] ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...