Check for Subarray in JavaScript
Here are the different approaches to check for Subarray in JavaScript
Using String Conversion with join() - Best Method
This approach converts both arrays into strings and checks if the subarray string is contained within the master array string.
function checkSub(a, sub) {
return a.join(',').includes(sub.join(','));
}
let a = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]
console.log(checkSub(a, [777, 22, 22]));
Output
trueUsing a Closure with indexOf()
This approach uses a closure to keep track of the index for searching within the master array. It ensures that the elements of the subarray appear in the same order within the master array.
function subArray(a, sub) {
return sub.every((i => v => i = a.indexOf(v, i) + 1)(0));
}
const a = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
console.log(subArray(a, [777, 22, 22]));
Output
trueSliding Window Technique
This approach slides over the master array using a window that matches the size of the subarray and checks for element-wise equality.
function subArray(a, sub) {
const subLength = sub.length;
for (let i = 0; i <= a.length - subLength; i++) {
let isMatch = true;
for (let j = 0; j < subLength; j++) {
if (a[i + j] !== sub[j]) {
isMatch = false;
break;
}
}
if (isMatch) return true;
}
return false;
}
let a = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3]
console.log(subArray(a, [777, 22, 22]));
Output
trueUsing Functional Approach
This approach uses Array.prototype.every() combined with indexOf() to ensure the order is preserved while checking for elements.
function isSubArray(main, sub) {
let index = -1;
return sub.every(
(element) => (index = main.indexOf(element, index + 1)) !== -1
);
}
const a = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
console.log(isSubArray(a, [777, 22, 22]));
Output
trueWhich Approach To Use?
- String Conversion: Best Method in terms of efficiency and usage
- Closure with indexOf(): Best for simple subarray checks with order preservation.
- Functional Approach: Concise and maintains order.
- Sliding Window: More robust and efficient for large arrays with repeated elements.