How can I count how many times a number appears in multiple arrays?

Asked

Viewed 106 times

0

I’m trying to make an application in which I enter a txt file with the results of the last mega Sena and parse it line by line. My goal is to see how many times a certain number has appeared since the beginning of the mega Sena. I’m using Javascript running on Node.Js

So far I’ve made it to the next:

2324 (05/12/2020) 02 16 19 31 43 60
2323 (02/12/2020) 20 27 35 39 50 59
2322 (28/11/2020) 02 05 10 29 34 41

\/

[ '02', '16', '19', '31', '43', '60' ],
[ '20', '27', '35', '39', '50', '59' ],
[ '02', '05', '10', '29', '34', '41' ],

But I don’t know how I can read each element and increment a counter relative to that element..

That’s my code so far:

let fs = require('fs')
let input = fs.readFileSync('./input.txt', 'utf-8')
let lines = input.split('\n')
let emptyLinesRemoved = lines.filter((element) => element.length > 0)
let onlyNumbers = emptyLinesRemoved.map((element) =>
  element.split(' ').slice(2)
)
console.log(onlyNumbers)

Any suggestions? Thanks in advance :)

  • If the input is similar to all arrays, what do you think about joining them all in an array and counting the occurrence of each number once? I thought about it, or else you make an array of arrays and traverse it by counting occurrences

  • I had thought of that too! Join all arrays using Concat... But I’m a bit in doubt on how to implement

  • Does this other question help you? It’s not exactly the same problem, but similar: Check how many times a number appears in the array

  • I think I got it! This question was exactly what I needed! Thank you Luiz Felipe. I will edit the solution

  • I cannot put a new answer, but the following snippet did work as expected: Let Count = {} onlyNumbers.foreach((array) => { array.foreach((element) => { if (!Count[element]) Count[element] = 1 Else Count[element] += 1 }) })

1 answer

0

Assuming that onlyNumbers is already an array of arrays, since the Map method returns an array, I think you can do the following:

first, to concatenate the arrays:

var mergedArray = [].concat.apply([], onlyNumbers);

then, for easy counting we will order the resulting array:

mergedArray.sort();

to finish, you can count the occurrences of each number so:

var occurrences = {};

for (var i = 0; i < mergedArray.length; i++) {
  var num = mergedArray[i];
  occurrences[num] = occurrences[num] ? occurrences[num] + 1 : 1;
}
  • This solution causes all numbers to have 1 in occurences

  • @Cayoeduardo sorry, there was an error in the code, already corrected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.