-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfOccurrences.js
More file actions
31 lines (23 loc) · 921 Bytes
/
Copy pathNumberOfOccurrences.js
File metadata and controls
31 lines (23 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// DESCRIPTION:
// Write a function that returns the number of occurrences of an element in an array.
// This function will be defined as a property of Array with the help of the method Object.defineProperty, which allows to define a new method directly on the object (more info about that you can find on MDN).
// Examples
// var arr = [0, 1, 2, 2, 3];
// arr.numberOfOccurrences(0) === 1;
// arr.numberOfOccurrences(4) === 0;
// arr.numberOfOccurrences(2) === 2;
// arr.numberOfOccurrences(3) === 1;
Object.defineProperty(Array.prototype, 'numberOfOccurrences',{
value : function numberOfOccurrences(element) {
return this.filter((el) => el === element).length
}
});
// Different approach
Array.prototype.numberOfOccurrences = function (element) {
var counter = 0;
for (var i = 0; i < this.length; i++)
{
if (this[i] == element) { counter++; }
}
return counter;
}