0

i know it is a repeated Question but i can't figure the proper way to add an object to an array with checking if there is match or not like , this is a function that loops through an array of words and check if the entered word is in the array so increase its count by 1 , if not push this word to the array and set its count by 0

function addWord(request, response) {
  var data = request.params;
  var word = data.word;
  var reply;
for (i = 0; i < Words.length; i++){
    if (Words[i].type != word){
       reply = {
         msg: "not Found but added"
       };
      Words.push({"type": word , "count": 0});
     } else if (Words[i].type == word) {
       reply = {
         msg: "already Found and added"
       };
       Words.count++;

     }

    }




  var x = JSON.stringify(Words, null, 2);
  fs.writeFile('count.json', x, finished);

  function finished(){
    console.log('Yay')
  }

the problem is the output gives me four new elements not just one and with Count 1 not 0, lets say that i added the word Music the output is like so

[
  {
    "type": "physical",
    "count": 8
  },
  {
    "type": "WCAP",
    "count": 2
  },
  {
    "type": "BLQ",
    "count": 2
  },
  {
    "type": "unable",
    "count": 2
  },
 {
    "type": "music",
    "count": 1
  },
{
    "type": "music",
    "count": 1
  },
{
    "type": "music",
    "count": 1
  },
{
    "type": "music",
    "count": 1
  },
]
  • 2
    Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – guysherman May 01 '20 at 00:47

2 Answers2

1

The problem is that you first must loop over all the words before deciding if a word is in the list or not. You could fix your code to look like this:

var found = false

for (i = 0; i < Words.length; i++){
  if (Words[i].type == word){
    Words[i].count++
    reply = {
      msg: "already Found and added"
    };
    found = true;
    break;
  }
}

if (!found) {
  Words.push({"type": word , "count": 0});
  reply = {
    msg: "already Found and added"
  };
}

And just in case, here is a snippet with a simpler addWord function that might help you:

var Words = [];

function addWord(word) {
  for (var i=0; i < Words.length; i++) {
    if (word == Words[i].type) {
      Words[i].count++
      return
    }
  }
  
  Words.push({type: word, count: 0})
}

addWord('stack')
addWord('overflow')
addWord('stack')

console.log(Words)
Alejandro De Cicco
  • 1,216
  • 3
  • 17
0

try the following function:

function findWord(Words) {
  let found = Words.some(word => word.type == yourWord)
  return found;
}
Ebrahim Mansour
  • 363
  • 1
  • 4
  • 13