'Sorting array upon two criteria

Here's a data sample:

    Name          Code
1.  JOHNY          AG
2.  JOHNA          AJOH
3.  JOHN           BPO
4.  JAHN           JOH 

What I want is to sort it according to the following criteria, given a search string:

  I. Name starts with that string
 II. Code includes that string
III. If there is a tie, initial order should be kept

For example,

"JOH" should return: 2 1 3 4 whereas "J" should return: 2 4 1 3

I have tried that but with no luck...

myArray.sort(function compare(firstElem) {   
      if (firstElem.name.startsWith(text)) 
        return -1;
      if (firstElem.code.includes(text)) 
        return -1;
      return 0;
   })


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source