Reputation: 368
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
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