Function
Identifies the type of array elements
The array or array-like object of elements to be searched.
The (ordered) array or array-like object of elements to locate within theArray.
OptionalfromIndex: number
The index to start the search at. If the provided index value is a negative number, it is taken as the offset from the end of theArray. Default: 0 (search from the start).
The index within theArray at which subset fully matches (or matches theArray's available elements from that position), or -1 if no such position exists. Returns fromIndex (normalized to a valid index, or the length of theArray) if subset is empty.
arrIndexOfSubset([1, 2, 3, 4, 5], [3, 4]); // 2
arrIndexOfSubset([1, 2, 3, 4, 5], [4, 3]); // -1
arrIndexOfSubset(["a", "b", "a", "b", "c"], ["b", "c"]); // 3
arrIndexOfSubset([1, 2, 3], [3, 4, 5]); // 2 (matches the available "3")
arrIndexOfSubset([1, 2, 3], []); // 0
arrIndexOfSubset("abcabc", ["c", "a"]); // 2
arrIndexOfSubset("abc", ["bc"]); // -1 (the characters are compared)
// Repeated values -- a plain indexOf() of the first element would land on index 0
let haystack = ["at foo", "at bar", "at foo", "at bar", "at baz"];
arrIndexOfSubset(haystack, ["at foo", "at bar", "at baz"]); // 2
The arrIndexOfSubset() method returns the index within
theArrayat whichsubsetfirst matches contiguously, comparing elements using strict equality (the same method used by the === or triple-equals operator).Unlike a simple
arrIndexOf()of the first element ofsubset, this continues searching later occurrences of that first element until it finds one where the whole sequence lines up (or exhauststheArray), which avoids landing on the wrong occurrence when values repeat -- for example matching one stack trace against another when recursive calls repeat identical lines.If
theArrayhas fewer remaining elements thansubsetfrom a candidate position, the comparison is limited to just those available elements -- so asubsetthat "runs off the end" oftheArrayis still considered a match against its available prefix. This makes it possible to match a shorter (eg. truncated) array against a longer one, or vice-versa. A full match is always found before a partial match at the end (which is only checked after every full position), unless thefromIndexis after the last full match, eg.arrIndexOfSubset([1, 2, 3, 1], [1, 2], 1)is3(the trailing1is a partial match).The elements are read by index, so for a string its characters (UTF-16 code units) are compared (a string element of
subsetnever matches a substring) and an empty slot of a sparse array is compared asundefined. As strict equality is usedNaNnever matches.