Output an array of elements whose occurrence times are greater than n

topic description

output an array of elements whose occurrence times are greater than n
add a findDuplicate (n) method for all array objects to return a list of elements whose occurrence frequency > = n in the array

[1, findDuplicate (2) = > [1]
[1, findDuplicate (5) = > []
[1, 2, 3, 4, 4, 1, 2, 2, 2] = > findDuplicate (- 1) = > [1, 2, 3, 4, 4]

Mar.12,2022

there are a lot of similar questions on es5 and so.


if (!Array.prototype.findDuplicate) {
    Object.defineProperty(Array.prototype, 'findDuplicate', {
        value: function (n) {
            if (this === void 0 || this === null) {
                throw new TypeError('this is null or not defined');
            };
            var t = Object(this);
            var len = t.length >>> 0;
            var obj = {};
            var result = [];
            for(let i = 0; i < len; iPP) {
                obj[t[i]] = (obj[t[i]] || 0)+1;
                if(obj[t[i]] == n) {
                    result.push(t[i]);
                }
            }
            return result;
        }
    });
}

Test case:
[1, br 2, 3, 4, 1, 1, 2, 2, 2] .findDuplicate (2) = > [1]
[1, 2, 2] < 2] .findDuplicate (5) = > []
[1, 2, 3, 4, 4, 1, 2, 2, 2] .findDuplicate (- 1) = > [1, 2, 3, 4]

Menu