- 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
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' } ]
- Related Articles
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Constructing a sentence based on array of words and punctuations using JavaScript
- Modify an array based on another array JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Sorting Array based on another array JavaScript
- Sort object array based on another array of keys - JavaScript
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Get range of months from array based on another array JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- How to find specific words in an array with JavaScript?
- Validating string with reference to array of words using JavaScript
- Filter an object based on an array JavaScript
- Reversing the order of words of a string in JavaScript
- Compute the truth value of an array XOR another array element-wise based on conditions in Numpy

Advertisements