-1

Good afternoon, I am trying to make a method that tells me the number of elements an Array has that starts with "RT:"

For this I have developed the following code:

public getRowsRTs(idProyecto){

    this.twitterService.getTargets().subscribe((data) => {

        this.Twitter = data;

    });
   let countRT = this.Twitter.filter( tweet => tweet.message.startsWith("RT:")).length;

   return countRT;
    }
}

Here, data returns all the Documents that Mongo extracts, and puts them in the Twitter Array that I have defined at the beginning of the component. Within this Array each element has different attributes, such as _id, message, date ... I want you to tell me how many of those documents, the message value, begins with RT: and to return it to me, this code , it does not give me any problem, but it does not give me absolutely nothing, I do not know if someone could help me.

Ramón Devesa
  • 387
  • 2
  • 3
  • 10
  • Is your property called `Array`? Can you give it a different name? Maybe `array`. And access the message with `array[i].message`. – ConnorsFan Mar 20 '20 at 20:35
  • 2
    Please provide a [mre] showing how you are defining `Array` and what kind of content it has in it. – Heretic Monkey Mar 20 '20 at 20:37
  • Answered quickly so I didn't think about it but there are a ton of dupes on this: https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements – Phil Mar 20 '20 at 20:41
  • 2
    Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – georgeawg Mar 20 '20 at 20:46
  • Of course what you refer to as your "test" doesn't return anything, because `JSON.stringify` is going to return [ or { in the first position. It is impossible to answer your question without knowing the input, and it's probably a duplicate as well. – Dexygen Mar 20 '20 at 20:54
  • The Array is an object that has an attribute that is message. – Ramón Devesa Mar 20 '20 at 23:24

2 Answers2

0

If the array is filled with strings, this should work:

let regixForRTStart = /^RT:/;
    startArray = ['RT:1', 'RT:2', 'Other', 'Stuff'],
    count = startArray.filter(item => regixForRTStart.test(item))

// length
console.log(count.length);
Phil
  • 10,948
  • 17
  • 69
  • 101
0

use filter and startsWith methods.

const arr = [
  { message: "abc" },
  { message: "RT:" },
  { message: "RT: 2" },
  { message: "test" }
];

const count = arr.filter(({ message }) => message.startsWith("RT:")).length;

console.log(count);
Siva K V
  • 10,561
  • 2
  • 16
  • 29