Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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));
Output
And the output in the console will be −
[ 'live', 'strong' ]
Advertisements