【发布时间】:2022-12-19 06:38:32
【问题描述】:
Given this arrays I want to check if "sequence" is a subsequence of "array", meaning all the numbers exist in the original array and in the same order:
array = [5, 1, 22, 25, 6, -1, 8, 10];
sequence = [1, 6, -1, 10];
Not sure why my code doesn't work.
function isValidSubsequence(array, sequence) {
let seqIdx = 0;
let arrId = 0;
for (const value of sequence ){
if (seqIdx === sequence.length) break;
if (array[arrId] === value) {
seqIdx++;
arrId++;
}
}
return seqIdx === sequence.length
}
【问题讨论】:
-
Subset... or substring?
-
This should work
const result = sequence.every(el => array.includes(el)); -
@HariHaravelan that won't account for order
-
@Phil Yes right, my bad
-
Thanks! it worked and makes sense
标签: javascript arrays subsequence