0

I have text and want to find the number of letters like 'a', 'i', and also the word 'it'. I've been able to find the number of letters 'a' and 'i', but for the word 'that' I can't find

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]

result_a = [];
result_i = [];
result_it = [];

for (let i = 0; i < words.length; i++) {
    for (let j = 0; j < text.length; j++) {
        if (words[i] == text[j] && words[i] == words[0]) {
            result_a.push(text[j]);
        } else if (words[i] == text[j] && words[i] == words[1]) {
            result_i.push(text[j])
        } else if (words[i] == text[j] && words[i] == words[2]) {
            result_it.push(text[j])
        }
    }
}

console.log(result_a.length) //13
console.log(result_i.length) //24
console.log(result_it.length) //0

The output I expect is the number of each word searched for, for example the number of 'a' in the text variable is 13

my code is too long, is there a more concise way? and how to find 'it'

Fajri
  • 3
  • 3

6 Answers6

0

I would just use a replacement trick here:

var text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis.";
var letters = ["a", "i"];

for (var i=0; i < letters.length; ++i) {
    var num = text.length - text.replace(new RegExp(letters[i], "g"), "").length;
    console.log("number of " + letters[i] + ": " + num);
}

If you want to search for it as a standalone word, then we need to search for \bit\b. But, this is very different from finding letters anywhere in the string.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • thanks for the response, but how to find 'it' in text – Fajri Nov 03 '22 at 06:22
  • Sir Tim, I have to ask one MCQ question from you about SQL is What is the meaning of "GROUP BY" clause in MySQL? and the options are : (a) Group data by column values (b) Group data by column and row values (c) Group data by row values (d) None of the above which option is correct here? – Sunderam Dubey Nov 03 '22 at 06:23
  • 1
    @SunderamDubey All SQL operations are row set based. So `GROUP BY` aggregates rows, not columns. – Tim Biegeleisen Nov 03 '22 at 06:24
  • @Fajri If you want to count occurrences of `it`, then do a regex search on `\bit\b` as my answer mentions. Not the same thing as counting letters. – Tim Biegeleisen Nov 03 '22 at 06:25
0

Just use RegExp for finding all match and get length

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]

for (var i=0; i < words.length; i++) {
    regexWord = new RegExp( words[i], 'g');
    var count = ((text || '').match(regexWord) || []).length
     
    console.log("number of " +  words[i] + ": " + count);
} 
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
0

You can use an object to keep track of the count. Not the most efficient solution but readable and should be fine if the inputs are not large.

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ['a', 'i', 'it'];
let wordCount = {
  'a': 0,
  'i': 0,
  'it': 0
};

for (let i = 0; i < text.length; i++) {
  for (const word of words) {
    if (text.substring(i).startsWith(word)) {
      wordCount[word]++;
    }
  }
}
Zakaria Ahmed
  • 54
  • 2
  • 7
0

First Solution:

Counting occurrence of each searchElement, regardless of char or word, as a substring in text.

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let searchElement = ["a", "i", "it"]
var wordToCount = {};

searchElement.forEach( word => {
  let searchText = new RegExp(word, 'g')
  var matchCount = (text.match(searchText) || []).length;
  wordToCount[word] = matchCount;
});

for (const [key, value] of Object.entries(wordToCount)) {
  console.log(key, value);
}

Second Solution:

In case the searchElemement is a character counting its occurrence. Otherwise, searching it as a word.

let text = "Lorem ipsum dolor sit amet it conseitctetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt it maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let searchElems = ["a", "i", "it"]

// handles character occurance count
var wordToCount = {};
let searchChars = searchElems.filter(word => word.length === 1)
searchChars.forEach( char => {
  let searchText = new RegExp(char, 'g')
  var matchCount = (text.match(searchText) || []).length;
  wordToCount[char] = matchCount;
});

// handles word occurance count
let textTokens =  text.split(" ");
let searchWords = searchElems.filter(word => word.length > 1)
let searchWordsSet = new Set(searchWords)
textTokens.forEach( word => {
    if (searchWordsSet.has(word))
      wordToCount[word] = 
          wordToCount[word] != undefined ? wordToCount[word] + 1: 1
})

for (const [key, value] of Object.entries(wordToCount)) {
   console.log(key, value);
}
tanmoy
  • 1,276
  • 1
  • 10
  • 28
  • 2
    This logic isn't completely correct, because it is searching for `it` as a substring, rather than as a word. You should clarify what your answer is doing. – Tim Biegeleisen Nov 03 '22 at 06:34
  • 1
    Handled that case as well in the second solution. Though I think he is looking for the substring search solution. – tanmoy Nov 03 '22 at 08:13
0

When you use for cycle on text string text[j] is one character in that string and when you compare it to words[i] it matches because in this case

let words = ["a", "i", "it"]

they are one characters, but if add word there, for example the word 'that' it will try to compare word 'that' to every single character from text string separatly

you can change it like this

function getCount(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes.length;
}
levani
  • 1
0

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]

result_a = 0;
result_i = 0;
result_it = 0;

for (let i = 0; i < text.length; i++) {
        if (text[i] == words[0]) 
           result_a++;
       if(text[i] == words[1]) 
           result_i++;
        if (text[i] == words[2][0] && text[i+1] == words[2][1]) 
           result_it++;        
}

console.log(result_a) //13
console.log(result_i) //24
console.log(result_it) //4