-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathforArrayProcessing.js
570 lines (552 loc) · 18.3 KB
/
forArrayProcessing.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/**
* [Tanaike](https://tanaikech.github.io/)
* [GitHub](https://github.com/tanaikech/UtlApp)
*/
/**
* ### Description
* When the inputted array is 2 dimensional array, true is returned.
*
* ### Sample script
* ```
* const array1 = ["", [1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const res1 = UtlApp.is2DimensionalArray(array1); // false
*
* const array2 = [[1, 2, 3], [1, 2], [1]];
* const res2 = UtlApp.is2DimensionalArray(array2); // true
* ```
*
* @param {Array} array 2 dimensional array.
* @return {Boolean} When the inputted array is 2 dimensional array, true is returned.
*/
function is2DimensionalArray(array) {
return array.every(r => Array.isArray(r));
}
/**
* ### Description
* When the inputted 2 dimensional array is the uniformed array, true is returned.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const res1 = UtlApp.isUniform2DArray(array1); // true
*
* const array2 = [[1, 2, 3], [1, 2], [1]];
* const res2 = UtlApp.isUniform2DArray(array2); // false
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Boolean} When the inputted 2 dimensional array is the uniformed array, true is returned.
*/
function isUniform2DArray(array, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
return new Set(array.map(r => r.length)).size == 1 ? true : false;
}
/**
* ### Description
* Make all array in 2 dimensional array uniforming the same length.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const res1 = UtlApp.uniform2DArray(array1);
* console.log(res1); // [ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
*
* const array2 = [[1, 2, 3], [1, 2], [1]];
* const res2 = UtlApp.uniform2DArray(array2);
* console.log(res2); // [ [ 1, 2, 3 ], [ 1, 2, null ], [ 1, null, null ] ]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {*} empty Value used in the added element. Default is null.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Uniformed array.
*/
function uniform2DArray(array, empty = null, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
const maxLen = Math.max(...array.map(r => r.length));
return array.map(r => [...r, ...Array(maxLen - r.length).fill(empty)]);
}
/**
* ### Description
* Transpose 2 dimensional array.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const res1 = UtlApp.transpose(array1);
* console.log(res1); // [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3, 3, 3 ] ]
*
* const array2 = [[1, 2, 3], [1, 2], [1]];
* const res2 = UtlApp.transpose(array2);
* console.log(res2); // [ [ 1, 1, 1 ], [ 2, 2, null ], [ 3, null, null ] ]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Transposed array.
*/
function transpose(array, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
return array[0].map((_, col) => array.map(row => row[col] || null));
}
/**
* ### Description
* Split array every n length.
* Ref: https://tanaikech.github.io/2022/05/21/splitting-and-processing-an-array-every-n-length-using-google-apps-script/
*
* ### Sample script
* ```
* const size = 3;
* const array1 = ["a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "i1", "j1"];
* const res = UtlApp.splitArray(array1, size);
* console.log(res);
* ```
*
* Result is as follows.
*
* ```
* [
* [ 'a1', 'b1', 'c1' ],
* [ 'd1', 'e1', 'f1' ],
* [ 'g1', 'h1', 'i1' ],
* [ 'j1' ]
* ]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Transposed array.
*/
function splitArray(array, size) {
if (!array || !size || !Array.isArray(array)) {
throw new Error("Please give an array and split size.");
}
return [...Array(Math.ceil(array.length / size))].map(_ => array.splice(0, size));
}
/**
* ### Description
* Retrieve the specific columns from 2 dimensional array.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const columns = [2];
* const res = UtlApp.getSpecificColumns(array1, columns);
* console.log(res); // [ [ 2 ], [ 2 ], [ 2 ] ]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Array} columns 1 dimensional array. Give the specific column numbers you want to get. The 1st number is 1.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Retrieved specific columns.
*/
function getSpecificColumns(array, columns, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
if (!columns || !Array.isArray(columns) || columns.length == 0) {
throw new Error("Please set column numbers you want to retrieve.");
}
return array.map(r => columns.map(e => r[e - 1] || null));
}
/**
* ### Description
* Delete specific columns from 2 dimensional array.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const columns = [2];
* const res = UtlApp.deleteSpecificColumns(array1, columns);
* console.log(res); // [ [ 1, 3 ], [ 1, 3 ], [ 1, 3 ] ]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Array} columns 1 dimensional array. Give the specific column numbers you want to delete. The 1st number is 1.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Array deleted the specific columns.
*/
function deleteSpecificColumns(array, columns, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
if (!columns || !Array.isArray(columns) || columns.length == 0) {
throw new Error("Please set column numbers you want to retrieve.");
}
return array.map(r => r.filter((_, j) => !columns.includes(j + 1)));
}
/**
* ### Description
* Insert columns to 2 dimensional array.
*
* ### Sample script
* ```
* const array1 = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];
* const array2 = [[4, 5, 6], [7, 8, 9]];
* const column = 2;
* const res1 = UtlApp.insertColumns(array1, array2, column);
* console.log(res1); // [[1,4,5,6,2,3],[1,7,8,9,2,3],[1,null,null,null,2,3]]
*
* const res2 = UtlApp.insertColumns(array1, array2, column, true);
* console.log(res1); // [[1,4,5,6,2,3],[1,7,8,9,2,3],[1,null,null,null,2,3]]
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Array} insertArray 2 dimensional array you want to insert.
* @param {Number} column Column number you want to insert the array. The 1st number is 1. Default is 1.
* @param {Boolean} rep When you want to replace the column, please use true. Default is false. In this case, the columns are inserted.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Array} Array inserted the columns.
*/
function insertColumns(array, insertArray, column = 1, rep = false, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
if (!insertArray || !Array.isArray(insertArray) || insertArray.length == 0 || !is2DimensionalArray(insertArray)) {
throw new Error("Please set columns you want to insert.");
}
const t = transpose(array, false);
t.splice(column - 1, rep ? 1 : 0, ...transpose(insertArray, false));
return transpose(t, false);
}
/**
* ### Description
* Remove duplicated values from 1 dimensional array.
*
* ### Sample script
* ```
* const array1 = ["a1", "b1", "c1", "b1", "c1"];
* const res = UtlApp.removeDuplicatedValues(array1);
* console.log(res);
* ```
*
* Result is as follows.
*
* ```
* {
* "removeDuplicatedValues":["a1","b1","c1"],
* "duplicatedValues":["b1","c1"],
* "numberOfDuplicate":{"a1":1,"b1":2,"c1":2}
* }
* ```
*
* @param {Array} array 1 dimensional array.
* @return {Object} Object including removeDuplicatedValues, duplicatedValues and numberOfDuplicate.
*/
function removeDuplicatedValues(array) {
if (!Array.isArray(array)) {
throw new Error("Please use 1 dimensional array.");
}
const obj = array.reduce((m, e) => m.set(e, m.has(e) ? m.get(e) + 1 : 1), new Map());
const e = [...obj.entries()];
return {
removeDuplicatedValues: [...obj.keys()],
duplicatedValues: e.reduce((ar, [k, v]) => {
if (v != 1) ar.push(k);
return ar;
}, []),
numberOfDuplicate: Object.fromEntries(e)
}
}
/**
* ### Description
* Retrieve empty row index.
*
* ### Sample script
* ```
* const array1 = [["a1"], [2], [3], [4], [], [5], [], ["z"], [""], [7], [8]];
* const res = UtlApp.get1stEmptyRow(array1);
* console.log(res); // { topEmptyRow: 4, lastEmptyRow: 8 }
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Object} Object including the top empty row index and the last empty row index.
*/
function get1stEmptyRow(array, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
return {
topEmptyRow: array.findIndex(r => r.join("") == ""),
lastEmptyRow: array.length - 1 - array.reverse().findIndex(r => r.join("") == "")
}
}
/**
* ### Description
* Retrieve empty column index.
*
* ### Sample script
* ```
* const array1 = [["a1", "b1", "f", "d1", "aa", "h", "aa"], [2, 3, 4, 5], [3, 1, 1, , , 3], [4, 1, 1, 1], [1, 2, 3], [5, 1, 1], [1, 1, 1], ["z", 1, 1], [1, "b", 1, 1, ""], [7, 1, 1, 1], [8, 6, 5, 4, 3]];
* const res = UtlApp.get1stEmptyColumn(array1);
* console.log(res); // { topEmptyColumn: 3, lastEmptyColumn: 7 }
* ```
*
* @param {Array} array 2 dimensional array.
* @param {Boolean} check Check whether the inputted array is 2 dimensional array. Default is true.
* @return {Object} Object including the top empty column index and the last empty column index.
*/
function get1stEmptyColumn(array, check = true) {
if (check && !is2DimensionalArray(array)) {
throw new Error("Please use 2 dimensional array.");
}
return array.reduce((o, r) => {
let top = r.findIndex(c => typeof c === "undefined" || c.toString() == "");
let last = r.length - 1 - r.reverse().findIndex(c => typeof c === "undefined" || c.toString() == "");
top = top == -1 ? r.length : top;
last = last == -1 ? 0 : last;
o.topEmptyColumn = o.topEmptyColumn < top ? o.topEmptyColumn : top;
o.lastEmptyColumn = o.lastEmptyColumn > last ? o.lastEmptyColumn : last;
return o;
}, { topEmptyColumn: Infinity, lastEmptyColumn: 0 });
}
/**
* ### Description
* Sum numbers in an array.
*
* ### Sample script
* ```
* const array1 = [1, 2, 3, 4, 5];
* const res = UtlApp.sum(array1);
* console.log(res); // 15
* ```
*
* @param {Array} array Input 1 dimensional array including number values.
* @param {Boolean} check Check whether the values of the inputted array is number. Default is true.
* @return {String} int8array.
*/
function sum(array, check = true) {
if (check && !(Array.isArray(array) && array.every(e => !isNaN(e)))) {
throw new Error("Please give an array including numbers.");
}
return array.reduce((n, e) => n += e, 0);
}
/**
* ### Description
* Compiling Continuous Numbers using Google Apps Script.
* Ref: https://tanaikech.github.io/2021/10/08/compiling-continuous-numbers-using-google-apps-script/
*
* ### Sample script
* ```
* const ar = [4, 5, 9, 3, 10, 5, 11, 7, 7, 13, 1];
* const res = UtlApp.compilingNumbers(ar);
* console.log(res)
* ```
*
* Result is as follows.
*
* ```
* [
* { start: 1, end: 1 },
* { start: 3, end: 5 },
* { start: 7, end: 7 },
* { start: 9, end: 11 },
* { start: 13, end: 13 }
* ]
* ```
*
* @param {Array} array Input array.
* @return {Array} Array including object like [{"start":1,"end":1},{"start":3,"end":5},{"start":7,"end":7},{"start":9,"end":11},{"start":13,"end":13}].
*/
function compilingNumbers(array) {
if (!(Array.isArray(array) && array.every(e => !isNaN(e)))) {
throw new Error("Please give an array including numbers.");
}
const { values } = [...new Set(array.sort((a, b) => a - b))].reduce((o, e, i, a) => {
if (o.temp.length == 0 || (o.temp.length > 0 && e == o.temp[o.temp.length - 1] + 1)) {
o.temp.push(e);
} else {
if (o.temp.length > 0) {
o.values.push({ start: o.temp[0], end: o.temp[o.temp.length - 1] });
}
o.temp = [e];
}
if (i == a.length - 1) {
o.values.push(o.temp.length > 1 ? { start: o.temp[0], end: o.temp[o.temp.length - 1] } : { start: e, end: e });
}
return o;
}, { temp: [], values: [] });
return values;
}
/**
* ### Description
* Converting 2 dimensional array to JSON object.
* Ref: https://tanaikech.github.io/2021/10/24/converting-values-of-google-spreadsheet-to-object-using-google-apps-script/
*
* ### Sample script
* ```
* const headers = ["header1", "header2", "header3"];
* const rows = [["a2", "b2", "c2"], ["a3", "b3", "c3"]];
* const res = UtlApp.convArrayToObject(headers, rows);
* console.log(res);
* ```
*
* Result is as follows.
*
* ```
* [
* { header1: 'a2', header2: 'b2', header3: 'c2' },
* { header1: 'a3', header2: 'b3', header3: 'c3' }
* ]
* ```
*
* @param {Array} headers Header array (1 dimensional array).
* @param {Array} rows Row array (2 dimensional array).
* @return {Object} JSON object.
*/
function convArrayToObject(headers, rows) {
if (!Array.isArray(headers) || !Array.isArray(rows) || !is2DimensionalArray(rows)) {
throw new Error("Please give an array of header and values.");
}
return rows.map(r => headers.reduce((o, h, j) => (o[h] = r[j], o), {}));
}
/**
* ### Description
* Converting 2-dimensional array as unpivot (reverse pivot).
* Ref: https://tanaikech.github.io/2023/05/11/unpivot-on-google-spreadsheet-using-google-apps-script/
*
* ### Sample script
* ```
* const values = [
* ["", "b1", "c1", "d1"],
* ["a2", 1, 2, 3],
* ["a3", 4, 5, 6],
* ["a4", 7, 8, 9],
* ["a5", 10, 11, 12]
* ];
* const res = UtlApp.unpivot(values);
* console.log(res);
* ```
*
* Result is as follows.
*
* ```
* [
* ['b1', 'a2', 1],
* ['b1', 'a3', 4],
* ['b1', 'a4', 7],
* ['b1', 'a5', 10],
* ['c1', 'a2', 2],
* ['c1', 'a3', 5],
* ['c1', 'a4', 8],
* ['c1', 'a5', 11],
* ['d1', 'a2', 3],
* ['d1', 'a3', 6],
* ['d1', 'a4', 9],
* ['d1', 'a5', 12]
* ]
* ```
*
* @param {Array} values 2 dimensional array.
* @return {Array} 2 dimensional array converted as unpivot (reverse pivot).
*/
function unpivot(values) {
if (!Array.isArray(values) || !is2DimensionalArray(values)) {
throw new Error("Please give an array of values.");
}
const [[, ...h], ...v] = values;
return h.flatMap((hh, i) => v.map(t => [hh, t[0], t[i + 1]]));
}
/**
* ### Description
* Reversing 2-dimensional array with unpivot.
* Ref: https://tanaikech.github.io/2023/05/11/unpivot-on-google-spreadsheet-using-google-apps-script/
*
* ### Sample script
* ```
* const values = [
* ["b1", "a2", 1],
* ["b1", "a3", 4],
* ["b1", "a4", 7],
* ["b1", "a5", 10],
* ["c1", "a2", 2],
* ["c1", "a3", 5],
* ["c1", "a4", 8],
* ["c1", "a5", 11],
* ["d1", "a2", 3],
* ["d1", "a3", 6],
* ["d1", "a4", 9],
* ["d1", "a5", 12]
* ];
* const res = UtlApp.reverseUnpivot(values);
* console.log(res);
* ```
*
* Result is as follows.
*
* ```
* [
* [null, 'b1', 'c1', 'd1'],
* ['a2', 1, 2, 3],
* ['a3', 4, 5, 6],
* ['a4', 7, 8, 9],
* ['a5', 10, 11, 12]
* ]
* ```
*
* @param {Array} values 2 dimensional array.
* @return {Array} Reversed 2 dimensional array with unpivot.
*/
function reverseUnpivot(values) {
if (!Array.isArray(values) || !is2DimensionalArray(values)) {
throw new Error("Please give an array of values.");
}
const [a, b, c] = values[0].map((_, c) => values.map(r => r[c]));
const ch = [...new Set(a)];
const rh = [...new Set(b)];
const size = rh.length;
const temp = [[null, ...rh], ...[...Array(Math.ceil(c.length / size))].map(_ => c.splice(0, size)).map((vv, i) => [ch[i], ...vv])];
return temp[0].map((_, c) => temp.map(r => r[c]));
}
/**
* ### Description
* Calculate dot product from 2 arrays.
*
* ### Sample script
* ```
* const array1 = [1, 2, 3, 4, 5];
* const array2 = [3, 4, 5, 6, 7];
* const res = UtlApp.dotProduct(array1, array2);
* ```
*
* @param {Array} array1 1-dimensional array including numbers.
* @param {Array} array2 1-dimensional array including numbers.
* @return {Number} Calculated result of dot product.
*/
function dotProduct(array1, array2) {
if (!Array.isArray(array1) || !Array.isArray(array2)) {
throw new Error("Please give 2 arrays.");
}
return array1.reduce((t, e, i) => t += e * array2[i], 0);
}
/**
* ### Description
* Calculate cosine similarity from 2 arrays.
*
* ### Sample script
* ```
* const array1 = [1, 2, 3, 4, 5];
* const array2 = [3, 4, 5, 6, 7];
* const res = UtlApp.cosineSimilarity(array1, array2);
* ```
*
* @param {Array} array1 1-dimensional array including numbers.
* @param {Array} array2 1-dimensional array including numbers.
* @return {Number} Calculated result of cosine similarity.
*/
function cosineSimilarity(array1, array2) {
if (!Array.isArray(array1) || !Array.isArray(array2)) {
throw new Error("Please give 2 arrays.");
}
const dotProduct = array1.reduce((t, e, i) => t += e * array2[i], 0);
const magnitudes = [array1, array2].map(e => Math.sqrt(e.reduce((t, f) => t += f * f, 0))).reduce((t, f) => t *= f, 1);
return dotProduct / magnitudes;
}