
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
Order an Array of Words Based on Another Array in 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