Javascript sorting alphabetically corresponding to the beginning of a line, then alphabetically for the contained text

I need help sorting the data. Let's say I type β€œpiz” in the search box. I get in return an array with all elements containing "piz".

Now I want to display them in the following order:

pizza pizzeria apizzetto berpizzo 

First, the elements that begin with what I entered in alphabetical order, and then those that contain what I entered in alphabetical order.

Instead, if I sort them alphabetically, I get the following

 apizzetto berpizzo pizza pizzeria 

Does anyone know how to do this? Thanks for your help.

+5
source share
4 answers

You can split the data into two arrays, one of which begins with your input, and the other does not. Sort each individually, then combine the two results:

 var data = [ 'pizzeria', 'berpizzo', 'apizzetto', 'pizza' ]; function sortInputFirst(input, data) { var first = []; var others = []; for (var i = 0; i < data.length; i++) { if (data[i].indexOf(input) == 0) { first.push(data[i]); } else { others.push(data[i]); } } first.sort(); others.sort(); return(first.concat(others)); } var results = sortInputFirst('piz', data); 

You can see it working here: http://jsfiddle.net/jfriend00/nH2Ff/

+9
source

The correct complete solution:

 var data = [ 'pizzeria', 'berpizzo', 'apizzetto', 'pizza' ]; var _sortByTerm = function (data, term) { return data.sort(function (a, b) { return a.indexOf(term) < b.indexOf(term) ? -1 : 1; }); }; var result = _sortByTerm(data, 'piz'); 

If you want to sort objects, use this function:

 var _sortByTerm = function (data, key, term) { return data.sort(function (a, b) { return a[key].indexOf(term) < b[key].indexOf(term) ? -1 : 1; }); }; 
+3
source

Here's another one:

 var str = 'piz'; var arr = ['apizzetto','pizzeria','berpizzo','pizza']; arr.sort(function(a,b) { var bgnA = a.substr(0,str.length).toLowerCase(); var bgnB = b.substr(0,str.length).toLowerCase(); if (bgnA == str.toLowerCase()) { if (bgnB != str.toLowerCase()) return -1; } else if (bgnB == str.toLowerCase()) return 1; return a < b ? -1 : (a > b ? 1 : 0); }); console.log(arr); 
+1
source

Using reduce:

 const data = ['pizzeria', 'berpizzo', 'pizza', 'apizzetto']; data.sort(); const [first, others] = data.reduce(([a, b], c) => (c.indexOf(input) == 0 ? [[...a, c], b] : [a, [...b, c]]), [[], []]); const sortedData = (first.concat(others)); console.log(sortedData); 
0
source

Source: https://habr.com/ru/post/1412265/


All Articles