Count how many times a word appears on the JSON

Describe the problem/error/question

So I have a JSON like this
[

{

“0”: “3.498405882361112”,

“test”: “buy”

},

{

“0”: “93.33333333333334”,

“test”: “neutral”

},

{

“0”: “42147.91”,

“test”: “sell”

},

{

“0”: “42198.3”,

“test”: “sell”

},

{

“0”: “42149.0”,

“test”: “sell”

},

{

“0”: “42154.83”,

“test”: “sell”

},

{

“0”: “42148.88”,

“test”: “sell”

},

{

“0”: “42169.82”,

“test”: “sell”

},

{

“0”: “99.83216710550379”,

“test”: “sell”

},

{

“0”: “-42152.810000000005”,

“test”: “sell”

}

]
I want to count how many times does 3 words “sell”, “buy”, “neutral” but I dont have any JS knowledge and the “Summarize” node doesnt support my request.

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

Hi @DuyBowl :wave: Welcome to the community :tada:

I think you’re looking for something like this:

2 Likes

Thanks a lot! It worked flawlessly. By the way can you explain how the code works? I’m learning Javascript now so I kinda want to know how the code works.

Get access to data

First imported the data from the previous steps and assigned it to data :
const data = $input.all();

Create Object

He created an object named wordCounts that holds the values buy, neutral, and sell :
const wordCounts = { buy: 0, neutral: 0, sell: 0, };

Loop over data

Then he looped over the data and incremented each variable in wordCounts whenever the word appeared.

Object.values(data).forEach((item) => is running the function in the following curly braces for each item in the json. So this code block runs for each piece of data.

const text = item?.json?.test.toLowerCase(); Saves the spot in the json we expect to find buy, sell, or neutral to the variable text. This is just so it’s easier to work with.

If statements

Then we just run if statements to increment the count in the variables if the data matches. For example:

if (text.includes("buy")) {
wordCounts.buy++;
}

if (text.includes("buy")) runs the code in the following {} if it’s true.

Syntax Explanation

wordCounts.buy++; adds one to the variable.

wordCounts.buy is just a way to access the variable that’s inside of the wordCounts object.

++ is just shorthand for adding one.
wordCounts.buy++; is the same thing as wordCounts.buy = wordCounts.buy + 1;

Get the data back to the node

Then return { wordCounts }; simply returns to object wordCounts back to the result of the node



Feel free to ask any follow up questions. I am also a self taught coder, keep at it :grin:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.