Skip to content

Commit dcb6e6b

Browse files
authored
Count elements in an array
1 parent 548d9ae commit dcb6e6b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,27 @@ function func(a,b){
227227
console.log(shuffle);
228228
```
229229
230+
# Count elements in an array
231+
232+
233+
```javascript
234+
const myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango']
235+
236+
//first option
237+
const countMyFruits = myFruits.reduce((countFruits,fruit) => {
238+
countFruits[fruit] = ( countFruits[fruit] || 0 ) +1;
239+
return countFruits
240+
},{} )
241+
console.log(countFruits)
242+
// { Apple:3, Banana:1, Mango:2, Orange:1 }
243+
244+
//seconf option
245+
const fruitsCounter = {};
246+
247+
for( const fruit of myFruits ){
248+
fruitsCounter[fruit] = fruitsCounter[fruit] ? fruitsCounter[fruit]+1 :1;
249+
}
250+
251+
console.log(fruitsCounter)
252+
// { Apple:3, Banana:1, Mango:2, Orange:1 }
253+
```

0 commit comments

Comments
 (0)