简体   繁体   中英

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'.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM