Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many times a value exists in an array [duplicate]

Tags:

javascript

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";
        }
    }
}
like image 787
Theskils Avatar asked Oct 14 '16 10:10

Theskils


People also ask

How do I count occurrence of duplicate items in array?

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 .

How do you count occurrences in an array?

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 .

Can array have duplicate values?

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.


2 Answers

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
like image 56
kevin ternet Avatar answered Nov 07 '22 00:11

kevin ternet


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; }
like image 27
Nina Scholz Avatar answered Nov 07 '22 02:11

Nina Scholz