I need to sort an array by the following order based on a search term.
- Exact string.
- Starts with.
- Contains.
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?
aandb. Your current algorithm just returns-1or0for all your array elements.because it looks like it's not meant to use with cases like thatit looks like a bigger problem (and maybe the core of your problem) is that your sorting function is returning results that are not logically equivalent! You should be returning-1,0but also1. Right now you only return one of two values - two objects are equal or smaller. It's functionally equivalent to returning a boolean as you still only have two outcomes.0if the term is nowhere to be found. Not that it makes it better.