查找数组中的元素是否与另一个数组的元素连续



我想知道数组 A 的元素相对于数组 B 是否连续。例如

["9:00 AM", "9:30 AM", "10:00 AM"] 

在以下方面是连续的

["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM"]

["9:00 AM", "10:30 AM", "11:00 AM"]

莫。

如果数组 A 的元素是连续的,则返回索引。例如

let all_appointments = ["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM"];
console.log(all_appointments.indexOf(["9:00 AM", "9:30 AM", "10:00 AM"]))

应该打印0

function foobar(a, b) {
const g = "__t(T.Tt)__";
return b.join(g).indexOf(a.join(g)) === 0 ? 0 : undefined;
}

编辑:添加了悲伤的柯比以减少误报的机会

如果"引用数组"不能包含重复项,这应该可以满足您的需求:

const indexOfArray = (needle, haystack) => {
if (!needle.length) {
return 0; // debatable
}
if (!haystack.length) {
return -1; // debatable
}
const haystackOffset = haystack.indexOf(needle[0]);
if (haystackOffset < 0) {
return -1;
}
for (let needleIndex = 1; needleIndex < needle.length; needleIndex++) {
const haystackIndex = needleIndex + haystackOffset;
if (haystack.length <= haystackIndex) {
return -1;
}
if (needle[needleIndex] !== haystack[haystackIndex]) {
return -1;
}
}
return haystackOffset;
};

例:

const haystack = ["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM"];
indexOfArray(["9:00 AM", "9:30 AM"], haystack); // 0
indexOfArray(["9:30 AM", "10:00 AM", "10:30 AM"], haystack); // 1
indexOfArray(["10:30 AM"], haystack); // 3
indexOfArray(["9:00 AM", "10:00 AM"], haystack); // -1
indexOfArray(["4:30 PM", undefined], haystack); // -1

最新更新