Leonardo Amigoni
Leonardo Amigoni

Reputation: 2317

Javascript sort alphabetically matching the beginning of string then alphabetically for contained text

I need help sorting through some data. Say I type "piz" in a searchfield. I get in return and array with all the entries that contain "piz".

I now want to display them in the following order:

pizza 
pizzeria
apizzetto
berpizzo

First the items that start with what I typed in alphabetical order then the ones that contain what I typed 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.

Upvotes: 10

Views: 8574

Answers (5)

Alex Desroches
Alex Desroches

Reputation: 11

Here's how I used the top voted answer to make my search function use a normalized set of data. It removes accents before comparing strings and is also case insensitive.

function getAutocompleteNormalizedMatches(userInput, array) {
    const normalizedInput = getNormalizedString(userInput);
    let normalizedListItem;
    let startsWith = [];
    let anywhere = [];
    for (let i = 0; i < array.length; i++) {
        normalizedListItem = getNormalizedString(array[i]);
        if (normalizedListItem.indexOf(normalizedInput) === 0) {
            startsWith.push(array[i])
        } else if (normalizedListItem.includes(normalizedInput)) {
            anywhere.push(array[i])
        }
    }
    startsWith.sort();
    anywhere.sort();
    return startsWith.concat(anywhere);
}


const getNormalizedString = function (str) {
    str = str.replace(/\s+/g, " ").trim();
    return (str ? removeDiacritics(str.toLowerCase()) : "");
};

To get the removeDiacritics() function, please refer to this link because it takes quite a bit of useless space if you guys don't need it: Remove accents diacritics in a string with JavaScript

Upvotes: 0

kingofbbq
kingofbbq

Reputation: 336

Using reduce:

const data = ['pizzeria', 'berpizzo', 'pizza', 'apizzetto'];

function sortInputFirst(input, data) {
    data.sort();
    const [first, others] = data.reduce(([a, b], c) => (c.indexOf(input) == 0 ? [[...a, c], b] : [a, [...b, c]]), [[], []]);
    return(first.concat(others));
}

const output = sortInputFirst('piz', data);
console.log(output)

Upvotes: 3

justtal
justtal

Reputation: 800

The right full solution is:

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 object sort, 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;
     });
 };

Upvotes: 7

jfriend00
jfriend00

Reputation: 707318

You can split the data into two arrays, one that starts with your input and one that doesn't. Sort each separately, 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 work here: http://jsfiddle.net/jfriend00/nH2Ff/

Upvotes: 15

inhan
inhan

Reputation: 7470

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);

Upvotes: 2

Related Questions