Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS sort array by three types of sorting

I need to sort an array by the following order based on a search term.

  1. Exact string.
  2. Starts with.
  3. 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?

like image 368
undefined Avatar asked Jan 01 '23 10:01

undefined


1 Answers

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);
like image 116
Nina Scholz Avatar answered Jan 08 '23 13:01

Nina Scholz