-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray-NthIndexOf.js
More file actions
35 lines (30 loc) · 974 Bytes
/
Array-NthIndexOf.js
File metadata and controls
35 lines (30 loc) · 974 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
29
30
31
32
33
34
35
Array.prototype.NthIndexOf = function(pattern, nth) {
const isAnArray = Array.isArray(pattern),
isNbOrStr = pattern.substring || pattern.toFixed;
if (nth) {
let index = -1;
while (nth-- && index++ < this.length) {
index = this.indexOf(pattern, index);
if (index < 0) break;
}
return index
} else {
const indexes = [];
for (let i = 0 ; i < this.length ; i++) {
if (isAnArray) {
if (pattern.includes(this[i])) indexes.push(i);
} else {
if (this[i] === pattern) indexes.push(i);
}
}
return indexes.length === 0 ? -1 : indexes.length === 1 ? indexes[0] : indexes;
}
}
// USAGE:
const arr = ["q","w","e","r","t","y","q","e"];
// Get all indexes of the letter "e"
arr.NthIndexOf("e"); // OUTPUT: [2,7]
// Get all indexes of letter "e" and "q"
arr.NthIndexOf(["e","q"]); // OUTPUT: [0,2,6,7]
// With a second parameter, get the index of the nth letter "q" (second one in this example)
arr.NthIndexOf("q", 2); // OUTPUT: 6