How to use Join with include In Javascript
If length of array are not equal , return false. We convert both arrays to strings using join() method and check if one is a substring of the other array concatenated with itself. If it is, return true, indicating that arr2 is a rotation of arr1. Otherwise it return false.
Example : To demonstrate checking if one array is a rotation of another array using join along with include.
function ArraysRotations(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
let str1 = arr1
.join('');
let str2 = arr2
.join('');
return (str1 + str1)
.includes(str2);
}
const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 1, 2, 3];
console.log(ArraysRotations(array1, array2));
Output
true
Time complexity: O(n + m + m * n)
Space complexity: O(n + m)
JavaScript Program to Check if one Array is a Rotation of Another
JavaScript has various inbuilt methods using which one can check whether one array is simply a rotation of another given array. Below is the example given to understand the problem clearly
Example:
Input
1 2 3 4 5
4 5 1 2 3
Output
True
There are different approaches to checking if one array is a rotation of another array which are described as follows:
Table of Content
- Using concatenation
- Using Join with include
Contact Us