- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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' ]
- Related Articles
- Finding squares in sorted order in JavaScript
- Last Substring in Lexicographical Order in C++
- Python Pandas - Return a sorted copy of the index in descending order
- How to Sort Elements in Lexicographical Order (Dictionary Order) in Golang?
- C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Swift Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Haskell Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Sort the words in lexicographical order in Python
- Sort the words in lexicographical order in C#
- Sort the words in lexicographical order in Java
- K-th Smallest in Lexicographical Order in C++
- JavaScript - Check if array is sorted (irrespective of the order of sorting)
- Merge two sorted arrays to form a resultant sorted array in JavaScript

Advertisements