5
I have an array with the following values:
let arrey = ["1","1","1","2","2","2"];
As it is possible to check how many times the number 1 appears and how many times the number 2 appears, for example, these numbers are changed each time I run my program, I need to check how many times the specified number appeared in the array, or the return should be another one like that:
let arrey2 = [
{
"numero": 1,
"quantidade": 3
},
{
"numero": 2,
"quantidade": 3
}
]
The code:
function itemCount(arrey){
let valor = arrey[0];
let length = arrey.length
let index = []
let contador = 0
let x = 0
let bol;
while(x < length){
for(let i = 0; i < arrey.length; i++){
if(arrey[x] === valor){
console.log(arrey[x])
contador += 1
}
}
let obj = {
"produto_id": arrey[x],
"quantidade": contador
}
if(index.length > 0){
index.forEach(itemArrey => {
if(itemArrey.produto_id === obj.produto_id){
bol = false;
}else{
bol = true;
}
});
if(bol == true){
index.push(obj);
}
}else if(index.length == 0){
index.push(obj);
}
x++
}
return index;
}
Passing the following array as input:
let arrey = ['1','1','2','2','2'];
intemCount(arrey);
The output of this my code is as follows:
(2) [{…}, {…}]
0: {produto_id: "1", quantidade: 5}
1: {produto_id: "2", quantidade: 10}
length: 2
__proto__: Array(0)
Wow! Just awesome! Thank you so much for giving me this class, I was complicating things too much when it wasn’t this seven-headed animal that I was thinking about. In addition to giving me a lesson passed me new knowledge in JS. Thank you very much!!!!!
– Joao Lima