Skip to content

Commit 5ec0a45

Browse files
authored
Merge pull request #24 from devvsakib/devvsakib
L-I problem added
2 parents 79845e4 + f31aa20 commit 5ec0a45

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# 0005 mostFrequentItem ( L-I )
2+
3+
## Problem
4+
5+
Given an array of items, return the most frequent item.
6+
7+
8+
## Test Cases
9+
10+
- Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], Output: 1
11+
- Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1], Output: 1
12+
- Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], Output: 1
13+
14+
15+
## Solution
16+
17+
```javascript
18+
19+
const mostFrequentItem = arr => {
20+
const obj = arr.reduce((acc, curr) => {
21+
if (acc[curr]) {
22+
acc[curr]++
23+
} else {
24+
acc[curr] = 1
25+
}
26+
return acc
27+
}, {})
28+
const max = Math.max(...Object.values(obj))
29+
return Object.keys(obj).filter(key => obj[key] === max)
30+
}
31+
32+
console.log(mostFrequentItem(arr))
33+
```
34+
35+
36+
## How it works
37+
38+
- Create an object with the number of times each item appears in the array
39+
- Get the maximum value of the object
40+
- Return the keys of the object that have the maximum value
41+
42+
43+
## References
44+
45+
- [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)
46+
- [Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
47+
- [Object.values()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
48+
- [Math.max()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max)
49+
- [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
50+
51+
52+
## Problem Added By
53+
54+
- [GitHub](https://www.github.com/devvsakib)
55+
- [LinkedIn](https://www.linkedin.com/in/devvsakib)
56+
- [Twitter](https://twitter.com/devvsakib)
57+
58+
59+
## Contributing
60+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
61+
62+
Please make sure to update tests as appropriate.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1]
2+
3+
const mostFrequentItem = arr => {
4+
const obj = arr.reduce((acc, curr) => {
5+
if (acc[curr]) {
6+
acc[curr]++
7+
} else {
8+
acc[curr] = 1
9+
}
10+
return acc
11+
}, {})
12+
const max = Math.max(...Object.values(obj))
13+
return Object.keys(obj).filter(key => obj[key] === max)
14+
}
15+
16+
console.log(mostFrequentItem(arr))

0 commit comments

Comments
 (0)