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' }
]

Updated on: 21-Aug-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements