 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Order an array of words based on another array of words JavaScript
Let’s say, we have the following array of objects sorted according to its id property −
const unordered = [{
   id: 1,
   string: 'sometimes'
}, {
   id: 2,
   string: 'be'
}, {
   id: 3,
   string: 'can'
}, {
   id: 4,
   string: 'life'
}, {
   id: 5,
   string: 'tough'
}, {
   id: 6,
   string: 'very'
}, ];
And another array of string like this −
const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];
We have to sort the first array so its string property have the same order of string as it is in the second array. Therefore, let’s write the code for this.
Example
const unordered = [{
   id: 1,
   string: 'sometimes'
}, {
   id: 2,
   string: 'be'
}, {
   id: 3,
   string: 'can'
}, {
   id: 4,
   string: 'life'
}, {
   id: 5,
   string: 'tough'
}, {
   id: 6,
   string: 'very'
}, ];
const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];
const sorter = (a, b) => {
   return ordered.indexOf(a.string) - ordered.indexOf(b.string);
};
unordered.sort(sorter);
console.log(unordered);
Output
The output in the console will be −
[
   { id: 4, string: 'life' },
   { id: 1, string: 'sometimes' },
   { id: 3, string: 'can' },
   { id: 2, string: 'be' },
   { id: 6, string: 'very' },
   { id: 5, string: 'tough' }
]Advertisements
                    