0

I have a function that stores strings inside an array and after calculating which one is the most repeated it returns it to me. The problem is that now I also need to get the second most repeated and in case two elements are repeated the same number of times I need to get both elements. I have given it a lot of thought but I can't figure out how to do it.

I have tried to remove the most repeated element from the array once it has been returned and then run the same function again without that element, but I don't find it practical. I don't know if there is another way to do it, I hope you can help me, thank you very much in advance.

arrayTotal = [...result4, ...result7, ...result8, ...result10, ...result11, ...result12, ...result13, ...result14];
    var arrayOrder = arrayTotal.sort();
    console.log(arrayOrder);

    var map = {};
    var occurence = "";
    var valor_mayor = 0;

    if (typeof arrayOrder === "string") {
        arrayOrder = arrayOrder.split(" ");
    }

    for (let elemento of arrayOrder) {
        if (map[elemento]) {
            map[elemento]++;
        } else {
            map[elemento] = 1;
        }

    };

    for (let elemento in map) {
        if (map[elemento] > valor_mayor) {
            valor_mayor = map[elemento];
            occurence = elemento;
        }
    }
    console.log(valor_mayor);
    console.log(occurence);
Martijn
  • 15,791
  • 4
  • 36
  • 68
Rfh1551
  • 1
  • 1
  • I've translated your example partly to english, making it easier to read for most of us :) – Martijn Jan 11 '23 at 09:31
  • I've added a duplicate. They do it with integers, but sample principle, it requires minimal tweaking – Martijn Jan 11 '23 at 09:32
  • to add on top of that after having the map of occurrences for each value you should build a second map binding the number of occurrences to an array containing the values occurring that amount of time. So that you can eventually sort the keys and find out which one you mean to fetch according to their position – Diego D Jan 11 '23 at 09:40
  • Can you show me an example please? – Rfh1551 Jan 11 '23 at 10:00

0 Answers0