6

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";
        }
    }
}
Theskils
  • 159
  • 1
  • 8
  • no need of `return true;` – Jaydip Jadhav Oct 14 '16 at 10:47
  • Try `Array.prototype.some` and `Array.prototype.filter`. – Maxx Oct 14 '16 at 10:47
  • 1
    When you use `return`, you'll be completely exiting the function immediately. So the first time `tall === liste[i]`, the function will end which is probably the issue you're having right now. – Saad Oct 14 '16 at 10:49
  • Wow. Thank you saadq. Just started with Javascript so trying to figure out what it all does. Used return in the last functuin that was almost the same. So thank you so much! – Theskils Oct 14 '16 at 10:50

5 Answers5

7

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
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
  • OP has just started, so you should add caveat for ES6. Also, just a opinionated pointer, using arrow functions where `this` is not required is abusing a feature. This will add up to performance as it will take that extra bit in binding context. Again, this is just my viewpoint – Rajesh Oct 14 '16 at 10:57
4

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can try Thor Jacobsen's answer in following post.

You should also refer ninjagecko's answer as it highlights alternate ways.

Also a caveat, since you are fetching value from input, make sure to convert it to number before comparing it.

For Loop

var arr = [1, 2, 3, 4, 5, 2, 1, 4, 4, 5, 5, 2];

function search() {
  var searchVal = +(document.getElementById('txtValue').value || 0);
  var count = 0;
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] === searchVal)
      count++;
  }

  console.log(count)
}
<input type="text" id="txtValue">
<button onclick="search()">Get Count</button>

Array.filter

var arr = [1, 2, 3, 4, 5, 2, 1, 4, 4, 5, 5, 2];

function search() {
  var searchVal = +(document.getElementById('txtValue').value || 0);
  var count = arr.filter(function(item) {
    return item === searchVal
  }).length;
  console.log(count)
}
<input type="text" id="txtValue">
<button onclick="search()">Get Count</button>
Community
  • 1
  • 1
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88
  • @Rajesh it doesn't matter from where you got the solution, first concern is to solve the OP's problem, and one more thing, if SO provides you ability to downvote then use it only where required, no need to become oversmart – Amrinder Singh Oct 14 '16 at 10:55
  • Dear friend, SO is not about solving someone's problem. Its about helping everyone to learn new things along with solving problem. Second, if you are copying someones' answer, please give them credit and share that post's link. Everyone can refer it and find alternative approaches as well. – Rajesh Oct 14 '16 at 11:00
  • finding the solution for someone is also very helpful, a very few people try to do so, ok i agree with the thing i should post the link of original post also, but why downvoting?? could you please explain Mr. Rajesh?? – Amrinder Singh Oct 14 '16 at 11:03
  • Objective of SO is to enhance learning along with helping others. So when you choose to answer, please do not copy. If answer exist, mark as duplicate(soon you will have that privilege, if not already). If not, then make sure to add something extra. Try to explain **What and Why** for changes and provide reference links. Please don't make SO another facebook with same post, posted 10000 times. – Rajesh Oct 14 '16 at 11:23
0

Will this work for you

JSFiddle Link

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++;
    }
  }
  if (sum > 0) {
    document.getElementById("skrivUt12").innerHTML = "Tallet " + tall + " finnes " + sum + " antall ganger";
  } else {
    document.getElementById("skrivUt12").innerHTML = "Tallet " + tall + " finnes ikke";
  }
}
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Himanshu Tanwar
  • 906
  • 6
  • 18
0

Use Array.prototype.reduce() to build a new array of counts of matched value in liste. You can then test if the item you are looking for exists in this array and what the count of instances is:

var liste = [12,14,13,76,5,1,23,12,87,124,674,98,3,7,-3,5];
var counts = liste.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {})
var count = function(item){return counts[item] || 0;};
var exists = function(item){return !!counts[item];};

console.log(exists(13)); //true
console.log(exists(999)); //false
console.log(count(5)); //2
console.log(count(232)); //0
Moob
  • 14,420
  • 1
  • 34
  • 47