How to Define Custom Sort Function in JavaScript

How to define custom sort function in javascript?

It could be that the plugin is case-sensitive. Try inputting Te instead of te. You can probably have your results setup to not be case-sensitive. This question might help.

For a custom sort function on an Array, you can use any JavaScript function and pass it as parameter to an Array's sort() method like this:

var array = ['White 023', 'White', 'White flower', 'Teatr'];
array.sort(function(x, y) { if (x < y) { return -1; } if (x > y) { return 1; } return 0;});
// Teatr White White 023 White flowerdocument.write(array);

custom sort order on array of objects

If you have an arbitrary sort order, one option is to assign the order to an array and then use indexOf:

var sortOrder = ['n', 'a', 'u'];var myArray = [{    name: 'u'  },  {    name: 'n'  },  {    name: 'a'  },  {    name: 'n'  }];myArray.sort(function(a, b) {  return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name);});
console.log(myArray);

Creating a custom sorting function for use as an option in script

The sorting function should return a negative number if a should come before b, 0 if it shouldn't be changed, or a positive number if b should come before a. Here is one possible implementation, assuming the date is a predictable string with the format YYYY {{season}}.

// Putting the season in the keys for ease of use and assigning them values so we know which one comes first.
var seasonMap = {
'Spring/Summer': 0,
Winter: 1,
Fall: 2
};

var order = 'asc'; // ascending or descending

function sortFunction(a, b) {
var coefficient = order === 'asc' ? 1 : -1; // If the order you pass it is 'asc', the a positive coefficient will retain this function's ascending sorting order; otherwise it will invert this function.

// Convert the dates into arrays by splitting them by a space ' '
var aDateComponents = a._values.date.split(' '),
bDateComponents = b._values.date.split(' ');

// The 0th value of the array is the year; additionally convert it into a Number instead of a String
var aYear = Number(aDateComponents[0]),
bYear = Number(bDateComponents[0]);

// The 1st value of the array is the season; look up the value from the map object we created in the beginning so we know which season comes after which
var aSeasonNumber = seasonMap[aDateComponents[1]],
bSeasonNumber = seasonMap[bDateComponents[1]];

if (aYear !== bYear) {
// return aYear - bYear. If a > b this will put a after b. The coefficient will invert it if we're sorting descending.
return coefficient * (aYear - bYear);
}

if (aSeasonNumber !== bSeasonNumber) {
// Same thing here. Since the season was mapped to a number, we know which season comes first and can return a positive or negative difference.
return coefficient * (aSeasonNumber - bSeasonNumber);
}

// Don't change the order otherwise.
return 0;
}

You should also validate the date string first, and check if it's a valid season.

How to custom sort in JavaScript? Not alphabetical or numerical

A solution for more than only the listed words, with precedence of the listed words.

var data = [        'Salisbury', 'Charlotte', 'Frankfurt', 'Düsseldorf', 'Raleigh',        'Cary', 'Wilson', 'High Point', 'Wake', 'New Jersey'    ],    customSort = [        'Salisbury', 'High Point', 'Wake', 'Charlotte', 'Raleigh',        'Cary', 'Wilson'    ],    customLookup = customSort.reduce(function (r, a, i) {        r[a] = ('000'+i).slice(-4); return r;    }, {}),    customSortFn = function (a, b) {        return (customLookup[a] || a).localeCompare(customLookup[b] || b);    };
document.write('<pre>' + JSON.stringify(data.sort(customSortFn), 0, 4) + '</pre>');

Sort an object array by custom order

You can use the function sort along with the function indexOf.

var array = [  {   ID: 168,   NAME: "First name",   CODE: "AD"  },  {   ID: 167,   NAME: "Second name",   CODE: "CC"  },  {   ID: 169,   NAME: "Third name",   CODE: "CCM"  },  {   ID: 170,   NAME: "Fourth name",   CODE: "CR"  }],    item_order = ["CCM","CR","AD","CC"];
array.sort((a, b) => item_order.indexOf(a.CODE) - item_order.indexOf(b.CODE));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to custom sort function in javascript or other method?

You can create one object to define order of each letter and sort by that object.

var cars = ["a", "c", "r", "s"];var s = {c: 1, a: 2, r: 3, s: 4}var r = cars.sort((a, b) => s[a] - s[b]).join(',')
console.log(r)

Custom sort array to order object based on string - Javascript

You need to specify priority array first.

var priority = [ "mv", "b", "fw"];

Now sort your array based on this as

arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );

Demo

var arr = [{    "name": "Ricard Blidstrand",    "number": "5",    "position": "b"  },  {    "name": "Gustaf Thorell",    "number": "12",    "position": "fw"  },  {    "name": "Rasmus Bengtsson",    "number": "13",    "position": "mv"  }];
var priority = [ "mv", "b", "fw"];
arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );
console.log(arr);

Custom sort array in Javascript

You can simply use Arrays.sort() and use a order array to sort the array in the order specified by the order array.

Try the following:

var arr = [ { "key":"Certified?", "value":"Yes" }, { "key":"Language", "value":"EN" }, { "key":"Training-Place", "value":"City" }, { "key":"Training-Place", "value":"aaa" }, { "key":"Language", "value":"bbb" }];
var order = ["Language", "Certified?", "Training-Place"]; arr.sort((a,b)=> order.indexOf(a.key) - order.indexOf(b.key)); console.log(arr);


Related Topics



Leave a reply



Submit