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
// 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 theArray at which subset first 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 of subset, this continues searching later occurrences of that first element until it finds one where the whole sequence lines up (or exhausts theArray), 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 theArray has fewer remaining elements than subset from a candidate position, the comparison is limited to just those available elements -- so a subset that "runs off the end" of theArray is 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.