-1

just started learning JS and had a test about loops and wasn't successful in finding an answer to this: I would like to see how many times the number 1 appears in the arrray. All i was able to do is get a true answer when 1 appears in the array. Been trying to figure this out since last Wednesday.. Thanks!

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];

count = 1;

for (var i = 0; i < v.length; i++){

      console.log (count == v[i])

}
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
Yair
  • 27
  • 1
  • 1
  • 3
  • http://stackoverflow.com/questions/13389398/finding-out-how-many-times-an-array-element-appears – Booboobeaker Jan 30 '17 at 16:38
  • 1
    Studying some array tutorials and doing some searching would help. Basic research is expected before asking questions here – charlietfl Jan 30 '17 at 16:39
  • `count == v[i]` The reason this comes back as true is that its a like the same as saying `Is count the same value as the value in the index?` so if count = 1 and v[i] = 1 then that question above would have an answer of true. – ollie Jan 30 '17 at 16:47
  • @charlietfl, i used some array tutorials and loop tutorials but wasn't able to understand it thoroughly, As i'm trying to understand the questions that appeared in the test i had. – Yair Jan 30 '17 at 16:54
  • @ollie Thanks for the explanation! – Yair Jan 30 '17 at 16:55

5 Answers5

5

If you want to count the number of times a value appears in the array, you firstly need to initialise a variable outside of the loop (if you initialise in the loop, the value will be reset on each iteration of that loop). Secondly you need a conditional statement that you will check for, in this case if a value is equal to one. As its a loop, and more then one value in the array, we can get the current index's value like v[i] (which you correctly did). Now you need to plus one to your counter, counter++ is the same as counter = counter + 1;. Now the if statement i used below has the === this is an equals operator that also check to see if the two values are of the same type.

  var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];    
    var count = 0;

        for (var i = 0; i < v.length; i++){
            if(v[i] === 1){
                count++;
            }
        }
          console.log (count);
ollie
  • 255
  • 1
  • 2
  • 15
3

You can make use of the filter method which returns the array with specified condition and then you can do a count by using the length property.

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
console.log((v.filter(x => x === 1)).length);
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
  • 1
    Does the same job, but for someone starting to learn JS... might be too advanced, but thats my opinion. – ollie Jan 30 '17 at 16:40
  • 1
    learning method like `forEach, map, find, filter etc` would definitely help in writing concise and clear code. – Abhinav Galodha Jan 30 '17 at 16:40
  • 2
    for counting an item, creating a new array is a bit over the top. – Nina Scholz Jan 30 '17 at 16:47
  • 1
    Yes, this works, but as others have stated, for a newbie, it's too complex. It also doesn't really address why the OPs code doesn't work and it is excessive for such a simple task. – Scott Marcus Jan 30 '17 at 16:54
  • @NinaScholz - Curios to know which method would you suggest which would be more efficient in terms of performance and space. – Abhinav Galodha Jan 30 '17 at 16:58
  • you could use reduce and add the condition expression. – Nina Scholz Jan 30 '17 at 17:03
  • It doesn't answer the question at all, which specifically asks how to do it using a `for` loop. Even as an alternative, `.filter()` isn't a good choice. –  Jan 30 '17 at 17:09
  • @ Nina Scholz: I too looked at the reduce implementation, and i have doubt that it would also need the accumulator variable to be created which would be adding to more memory. I will try to test it. – Abhinav Galodha Jan 30 '17 at 17:13
2

Close! What you need to do is initialize a count variable and then iterate over the array. At each index, you check if the element matches the number. If it does, you increment the count

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];

var count = 0;
var number = 1;

for (var i = 0; i < v.length; i++){
    if (v[i] == number) {
        count++;
    }
}

console.log(count);
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
1

You can do this with a variety of techniques, but in your case, you need to actually check the array value for 1 as you loop, which you aren't doing.

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];

// Don't assume that there are any occurrences of 1 in the array
count = 0;

for (var i = 0; i < v.length; i++){
  // Test to see if the current array item is 1 and, if so, increment the counter
  
  // The "long-hand" way:
  //if(v[i] === 1){
  //  count++;
  //}
  
  // Above "if" could also be written using JavaScript's "ternary" operator as this:
  count = (v[i] === 1) ? ++count : count;
}

// The report should be after the loop has completed.
console.log ("1 appears in the array " + count + " times.")

Here's another (of many) techniques, but this one removes the loop, the if test and the counter completely. It also takes arrays out of the algorithm, which, in turn, can make the code much easier to understand:

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];

// Turn array into string and (using regular expressions) remove any char that is not 1
var s = v.join("").replace(/[0, 2-9]+/g, "");

// Just check the length of the string after removing non-1 chars:
console.log ("1 appears in the array " + s.length + " times.");
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

you have to increase the count, you are only checking if the count equals what the current item is

var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];

count = 0;

for (var i = 0; i < v.length; i++){
    var cur = v[i];          // < gets the current item
    if (cur == 1)            // < If the current item is 1
        count += 1;          // < Then increase the count by 1
    console.log (count);     // < Log what the count is

}
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37