Reputation: 6874
I need to sort an array by the following order based on a search term.
Code :
var arr = ['Something here Hello', 'Hell', 'Hello'];
var term = 'Hello';
var sorted = arr.slice().sort((a, b) => {
let value = 0;
if (a.startsWith(term)) {
value = -1;
}
if (a.indexOf(term) > -1) {
value = -1;
}
if (a === term) {
value = -1;
}
return value;
});
console.log(sorted);
The expected result is:
["Hello", "Hell", "Something here Hello"]
I'm not sure how to do this with the built-in sort function because it looks like it's not meant to use with cases like that. Any advice, please?
Upvotes: 4
Views: 1929
Reputation: 386680
You need a function which returns a value for the staged sorting.
Inside of the callback for sorting, you need to return the delta of the two values which reflects the relation between the two strings.
const compareWith = term => string => {
if (string === term) return 1;
if (term.startsWith(string)) return 2; // switch string and term
if (string.includes(term)) return 3; // use includes
return Infinity; // unknown strings move to the end
};
var array = ['Something here Hello', 'Hell', 'Hello'],
term = 'Hello',
order = compareWith(term);
array.sort((a, b) => order(a) - order(b));
console.log(array);
Upvotes: 9