I have an input element and when the user types on it my code searches through an array for the input value and prints its element if it exists and it works fine. The problem is when I'm printing it I want to sort the final array alphabetically but also I want the searched strings index value position matches to come up first, alphabetically, then the rest after them. To explain this better say my array is ['testB', 'testD', 'testC', 'dtest', 'cTest']
and the user searched for test
I want the final response array to be ["testB","testC","testD", "cTest", "dtest"]
is kind of sorted but it gives priority to same index positioned characters. How can I achieve this?
const myArray = ['testB', 'testD', 'testC', 'dtest', 'cTest']
let tempArray = []
$('input').on('input', function() {
tempArray = []
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].toLowerCase().includes($(this).val().toLowerCase())) {
tempArray.push(myArray[i])
}
}
//I want it to write ["testB","testC","testD", "cTest", "dtest"]
$('p').html(JSON.stringify(tempArray.sort()))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<p></p>