The first thing i am trying to do is find out if the number i type in the input exists in the array, this works.
The second thing I am trying to do is find out how many times it exists. Am I somewhat on the right path here?
<input id="hvorMange" type="number">
<button type="button" onclick="skrivUt12()">Finn tallet</button>
<p id="skrivUt12"></p>
var liste = [12,14,13,76,5,1,23,12,87,124,674,98,3,7,-3,5];
function skrivUt12(){
var tall = +document.getElementById("hvorMange").value;
var sum = 0;
for(i = 0; i < liste.length; i++) {
if (tall === liste[i]) {
sum++;
document.getElementById("skrivUt12").innerHTML = "Tallet " + tall + " finnes " + sum + " antall ganger";
return true;
}
else {
document.getElementById("skrivUt12").innerHTML = "Tallet " + tall + " finnes ikke";
}
}
}
To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .
Using the has() method In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.
First you filter your list to keep searched items and then return the length of filtered list:
var liste = [12,14,13,76,5,1,23,12,87,124,674,98,3,7,-3,5];
var count = (input, arr) => arr.filter(x => x === input).length;
console.log (count(12, liste)); // 2
You may better use an object for counting and use it for checking and displaying the count.
var liste = [12, 14, 13, 76, 5, 1, 23, 12, 87, 124, 674, 98, 3, 7, -3, 5],
count = {};
liste.forEach(function(a) {
count[a] = (count[a] || 0) + 1;
});
console.log(count);
if (count[12]) {
console.log('12 exist ' + count[12] + ' time/s');
} else {
console.log('12 does not exist.');
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With