RTVBasic
RTVBasic

Reputation: 35

How to check how many times a word shows up in JSON array

My JSON array looks like this:

    {
  "messages": [
    {
      "msg": "?",
      "name": "johndoe"
    },
    {
      "msg": "hello",
      "name": "johndoe",
    },
    {
      "msg": "twitt",
      "name": "johndoe"
    },
    {
      "msg": "hello everyone!",
      "name": "johndoe"
    },
    {
      "msg": "hello! how are you",
      "name": "johndoe"
    },
    {
      .........

I would like to know how I can check how many times the word "hello" shows up in this whole array, and then just return the number. Thank you for the help.

Upvotes: 1

Views: 297

Answers (4)

Maxime Girou
Maxime Girou

Reputation: 1570

You can use reduce

const arr = {
  "messages": [{
      "msg": "?",
      "name": "johndoe"
    },
    {
      "msg": "hello",
      "name": "johndoe",
    },
    {
      "msg": "twitt",
      "name": "johndoe"
    },
    {
      "msg": "hello everyone!",
      "name": "johndoe!!"
    },
    {
      "msg": "hello! how are you",
      "name": "johndoe!"
    }
  ]
};

const count = arr.messages.reduce((acc, m) => {
  if (m.name === "johndoe") {
    acc += 1;
  }
  return acc;
}, 0);
console.log(count)

//shorter version
const count2 = arr.messages.reduce((acc, m) => m.name === "johndoe" ? acc += 1 : acc, 0);
console.log(count2)


// EDIT : if you wanna search for "johndoe" string and the name value is "johndoe!!"
const count3 = arr.messages.reduce((acc, m) => {
  if (m.name.includes("johndoe")) {
    acc += 1;
  }
  return acc;
}, 0);
console.log(count3)

Upvotes: 1

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6749

Since it it's a valid JSON format it may as well be treated as a string (before parsing) if that's the case a simple regex would be enough to count the occurrences of particular string inside of it

const input = `{
  "messages": [
    {
      "msg": "?",
      "name": "johndoe"
    },
    {
      "msg": "hello",
      "name": "johndoe",
    },
    {
      "msg": "twitt",
      "name": "johndoe"
    },
    {
      "msg": "hello everyone!",
      "name": "johndoe"
    },
    {
      "msg": "hello! how are you",
      "name": "johndoe"
    }
  ]
}`;

function count(input, match){
  return (input.match(new RegExp(match, "g")) || []).length;
}

console.log("hello: ", count(input, "hello"));
console.log("johndoe: ", count(input, "johndoe"));

Upvotes: 0

karthikdivi
karthikdivi

Reputation: 3633

You need the following.

data.forEach(ele => {if(ele.msg.includes('hello')) counter++ });

Here is a demo https://onecompiler.com/javascript/3v2spaetr

Upvotes: 1

Sudhakar
Sudhakar

Reputation: 585

let helloCount = data.messages.filter(message=>{return message.msg.includes('hello')}).length;

Try above one

Upvotes: 2

Related Questions