Is there any way to count the number of occurrences in a jQuery array?

前端 未结 4 1556
失恋的感觉
失恋的感觉 2021-01-02 08:48

I have an array that I put together in jQuery and I\'m wondering if there is a way that I could find the number of occurrences of a given term. Would I have better results i

4条回答
  •  無奈伤痛
    2021-01-02 09:23

    If you have an array like this:

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

    And set your target value:

    var target = 1;
    

    Then you can find the number of occurences of target using:

    var numOccurences = $.grep(arr, function (elem) {
        return elem === target;
    }).length; // Returns 2
    

提交回复
热议问题