-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroupBy.js
More file actions
66 lines (58 loc) · 1.68 KB
/
groupBy.js
File metadata and controls
66 lines (58 loc) · 1.68 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const areEqual = function (item1, item2) {
if (areBothArrays(item1, item2)) {
return areArraysSimilar(item1, item2);
}
return item1 === item2;
};
const areArraysSimilar = function (array1, array2) {
for (let index = 0; index < array1.length; index++) {
if (array1[index] !== array2[index]) {
return false;
}
}
return true;
};
const isArrayOccured = function (items, elements) {
for (let index = 0; index < elements.length; index++) {
if (Array.isArray(elements[index])) {
return areArraysSimilar(items, elements[index]);
}
}
return false;
};
const notOccured = function (item, elements) {
if (Array.isArray(item)) {
return !isArrayOccured(item, elements);
}
return !elements.includes(item);
};
const areBothArrays = function (array1, array2) {
return Array.isArray(array1) && Array.isArray(array2);
};
const similarElements = function (elements, itemIndex) {
const group = [];
for (let pos = itemIndex; pos < elements.length; pos++) {
if (areEqual(elements[pos], elements[itemIndex])) {
group.push(elements[pos]);
}
}
return group;
};
const groupBy = function (elements) {
const similarElementsGroup = [];
for (let index = 0; index < elements.length; index++) {
if (notOccured(elements[index], elements.slice(0, index))) {
similarElementsGroup.push(similarElements(elements, index));
}
}
return similarElementsGroup;
};
const main = function () {
console.log(groupBy([1, 2, 1]));
console.log(groupBy([1, 2, 3]));
console.log(groupBy([2, 2, 3]));
console.log(groupBy([[2, 2], 3, 3, [2, 2], 1]));
console.log(groupBy([[2, 2], 3, [2, 2]]));
console.log(groupBy([[2, 2], 3, [2, 2], 3]));
};
main();