How to count repeated items with javascript?

Asked

Viewed 1,069 times

0

Example:

const cores = [{id: 1, cor: 'azul'}, {id: 2, cor: 'azul'}, {id: 3, cor: 'azul'}, {id:4, cor: 'verde'}, {id: 5, cor: 'verde'}, {id: 6, cor: 'azul'}, {id: 7, cor: 'verde'}, {id: 8, cor: 'marrom'}, {id: 9, cor: 'marrom'}];

Final object to be returned when counting the items repeated accordingly:

const objeto = [{cor: 'azul', total: 3}, {cor: 'verde', total: 2}, {cor: 'Azul', total: 1}, {cor: verde, total: 1}, {cor: 'marrom', total: 2}];

I broke my head a lot with map and filter and this was the result:

cores.map(item => item.cor).map(value => { if(value !== cor) { cor = value; count = 1; return value; } else { count = ++count; cor = value; } return count; });

(9) ["azul", 2, 3, "verde", 2, "azul", "verde", "marrom", 2]

Notice that I got the value and the final result of those that have quantities larger than 1. After the blue color, the number 2 and 3 are the counts made by the map above and 3 and the total of blue of the first occurrence. After this the green that has 2 occurrences, then the blue and the green that has only 1 occurrence more I could not get them to return the integer value 1, then the brown that has 2 repeated occurrences. After this I tried to redo in other ways only flawed codes.

  • What codes have you tried to do? Edit your question so we can better know how to help you.

1 answer

2


Do not use map, He’s not cut out for it.

map serves to transform array elements into something else. For example:

let x = [1, 2, 3];
console.log(x.map(n => n * 2)); // imprime o dobro dos números

In the above example I transformed each number into its double. map serves for this, and the important detail is that the result has the same number of elements as the original array (for each element, there is a corresponding result).

But in your case, this is not necessarily true. Your original array has 9 elements, and the result may have less, so map is not the most appropriate (filter also makes no sense, as it serves to choose array elements based on some criterion, but you don’t want to choose any, you just want to add the amounts of consecutive elements with the same color).

So it’s easier to make one for simple and check that the element is equal to the next (if it is, increment the count, otherwise add the total and start the count again):

const cores = [{id: 1, cor: 'azul'}, {id: 2, cor: 'azul'}, {id: 3, cor: 'azul'}, {id:4, cor: 'verde'}, {id: 5, cor: 'verde'},
 {id: 6, cor: 'azul'}, {id: 7, cor: 'verde'}, {id: 8, cor: 'marrom'}, {id: 9, cor: 'marrom'}];

let cont = [];
let total = 1;
for (let i = 0; i < cores.length; i++) {
    if (i < cores.length - 1 && cores[i].cor == cores[i + 1].cor) {
        total++;
    } else {
        cont.push({ cor: cores[i].cor, total: total });
        total = 1;
    }
}
console.log(cont);

Browser other questions tagged

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