Asker123
Asker123

Reputation: 368

How do I sort an array of strings, by the ascending occurence of a 'word' in the string? javascript

Let's say I have the following strings in an array:

let strings = ['cat bone Dog', 'Dogcat bone', 'cat Dog bone'];
.
.
.
.
return sortedString = ['Dogcat bone', 'cat Dog bone', 'cat bone Dog'];

I'm thinking of using localeCompare but I don't know how to specify to sort by a certain set of characters, in this case, I want to sort by the 'Dog'.

I can still have the word 'Dog' be attached to other words without spaces, like 'Dogcat bone'.

Upvotes: 1

Views: 675

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Split the string by spaces, and return the difference of the indexOf the word you're looking for in the array:

let strings = ['cat bone Dog', 'Dog cat bone', 'cat Dog bone'];
const getDogPos = string => string.split(' ').indexOf('Dog');

strings.sort((a, b) => getDogPos(a) - getDogPos(b));
console.log(strings);

If you want to sort by the position of the substring in the string, rather than the position of the word, then just use indexOf without splitting first:

let strings = ['cat bone Dog', 'Dogcat bone', 'cat Dog bone'];
const getDogPos = string => string.indexOf('Dog');

strings.sort((a, b) => getDogPos(a) - getDogPos(b));
console.log(strings);

Upvotes: 3

Related Questions