Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return a sorted array in lexicographical order in JavaScript
We are required to write a JavaScript function that takes two arrays, say arr1 and arr2. Our function should return a sorted array in lexicographical order of the strings of arr1 which are substrings of strings of arr2.
How It Works
The function iterates through arr1 and checks if each string is a substring of any string in arr2. If found, it adds the string to the result array and continues to the next string using a labeled continue statement.
Example
The code for this will be ?
const lexicographicalSort = (arr1 = [], arr2 = []) => {
let i, j;
const res = [];
outer: for (j = 0; j < arr1.length; j++) {
for (i = 0; i < arr2.length; i++) {
if (arr2[i].includes(arr1[j])) {
res.push(arr1[j]);
continue outer;
};
};
}
return res.sort();
};
const arr2 = ["lively", "alive", "harp", "sharp", "armstrong"];
const arr1 = ["xyz", "live", "strong"];
console.log(lexicographicalSort(arr1, arr2));
[ 'live', 'strong' ]
Step-by-Step Breakdown
Let's trace through the execution:
const arr1 = ["xyz", "live", "strong"];
const arr2 = ["lively", "alive", "harp", "sharp", "armstrong"];
// Check "xyz": not found in any string of arr2
// Check "live": found in "lively" and "alive"
// Check "strong": found in "armstrong"
console.log("Checking substrings:");
arr1.forEach(str => {
const found = arr2.some(target => target.includes(str));
console.log(`"${str}" is ${found ? 'found' : 'not found'} in arr2`);
});
Checking substrings: "xyz" is not found in arr2 "live" is found in arr2 "strong" is found in arr2
Alternative Approach Using Filter
A more concise solution using array methods:
const lexicographicalSortFilter = (arr1, arr2) => {
return arr1
.filter(str => arr2.some(target => target.includes(str)))
.sort();
};
const arr1 = ["xyz", "live", "strong", "abc"];
const arr2 = ["lively", "alive", "harp", "sharp", "armstrong"];
console.log(lexicographicalSortFilter(arr1, arr2));
[ 'live', 'strong' ]
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| For loop with labeled continue | Medium | Slightly better | Longer |
| Filter with some() | High | Good | Shorter |
Conclusion
Both approaches effectively find substrings and return them in lexicographical order. The filter method is more readable, while the loop version offers slightly better performance for large datasets.
