Count the number of odd elements in the JS array

Source: Internet
Author: User

How to count the number of odd elements in a JS array?

This is a question raised by the group of friends, most of the group of friends give the traversal and then the 2 modulo, the final result.

This kind of writing is the most easy to get, then there are no other ideas?

Here I provide another way of thinking, we know that the odd number is actually 1 3 5 7 9 as the end of the numbers, then as long as the statistics of the number of occurrences is enough, but the light such statistics easy to calculate, so we can first with commas together, with a comma to calculate, Because JS is not PHP so convenient to use the Substr_count function to count the number of occurrences of the string, so we directly use regular replacement, calculate the length difference to get the number, the code is as follows:

This idea is also my whim, the feeling is still some ingenious, after all, although this problem is simple, but assuming this array is very large, then its cycle difficulty is increased, and every time to take modulo operation, wasting a lot of performance, after all, even is not required to participate in the calculation, but do not participate in the calculation and do not know it is even So here is a direct substitution, then the length difference calculation can know exactly how many odd!

Count the number of odd elements in the JS array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.