0

hey guys new to javascript and trying to run a simple count procedure in arrays

i have built an array from some prompts and am now trying to run a loop through to count negative and positive numbers

i understand the for loop context, would i have to build another emtpy array and push results to it?

this is what i have written up so far...

let array2 = []
    for (let i = 0; i < numberCount; i++) {
        if (array[i] > 0) {
            i == 1
            array2.push(i)
        }
    }

any help appreciated, dont burn me to hard!

001
  • 13,291
  • 5
  • 35
  • 66
cc604
  • 1
  • 1
  • 2
  • What are you hoping `i == 1` will do here? I do not think it means what you think it means. – Wyck Feb 18 '21 at 18:38
  • no worries, the idea is that the variable would equal the value of 1, definately understand im not doing it right, hoping for some insight as im trying to understand how the language works. cheers – cc604 Feb 18 '21 at 18:44
  • If you are just counting, there is no need for another array. Just have 2 counters - one for negative and one for positive. `if (array[i] > 0) positiveCounter += 1;` – 001 Feb 18 '21 at 18:45
  • Consider `array.filter(n => n > 0).length` – Wyck Feb 18 '21 at 18:45
  • oh ok cool to see both options, i tend to overthink and think my original solution may be a bit overkill – cc604 Feb 18 '21 at 18:47
  • so from my understanding, the counter will increment 1 everytime the condition is met? does this make the counter the new variable? – cc604 Feb 18 '21 at 18:48
  • See also: https://stackoverflow.com/questions/6120931/how-to-count-certain-elements-in-array – Wyck Feb 18 '21 at 18:48

2 Answers2

0

Here is your code

let array = [0, 1, 2, -1, -4, 5, -12, -4]
let count = 0
for (let i = 0; i < array.length; i++) {
    if (array[i] < 0) {
        count = count + 1
    }

}
console.log(count)
-1

Please clear. what you want...

If you want to find the number of elements present in array , you can use .length property.

let array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
let arrayCount = array.length
  • it was more of gathering specific data based on an if statement, the counter function has worked for me right now. the idea was if an item in the array was < 0 then it would increment a count. Thanks for providing another look at the problem – cc604 Feb 18 '21 at 18:58