-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ6.js
More file actions
28 lines (26 loc) · 656 Bytes
/
Copy pathQ6.js
File metadata and controls
28 lines (26 loc) · 656 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
//Q6. Wrt. Code to find no. of occurrence of string/numbers in array.
//Arr = [1,2,3,1,3,2,2,1,1] o/p should be {1:3,2:3,3:2}
//Option 1
function getRepeatData(inputArr) {
var objArr = {};
for (let i = 0; i < inputArr.length; i++) {
if (objArr.hasOwnProperty(inputArr[i])) {
objArr[inputArr[i]] = objArr[inputArr[i]] + 1;
} else {
objArr[inputArr[i]] = 1;
}
}
console.log(objArr);
}
var inputArr = [1, 2, 3, 4, 1, 3, 2, 2];
getRepeatData(inputArr);
//Option 2
const count = {};
inputArr.forEach((element) => {
if (count[element]) {
count[element] += 1;
} else {
count[element] = 1;
}
});
console.log(count);