In JavaScript, I have an array of objects and an input value like this:
const inputVal = 'foo';
const objArray = [
{title: 'blahaa', type: 'foobar'},
{title: 'foobar', type: 'wohoo'},
{title: 'foobar', type: 'foobar'},
{title: 'foobar', type: 'aaaabaa'},
{title: 'foobar', type: 'moo'},
{title: 'aaah', type: 'foogoo'},
{title: 'foohiii', type: 'foobar'},
{title: 'aaah', type: 'foobar'},
{title: 'foodoo', type: 'aaaabaa'},
{title: 'gaaaaaah', type: 'foobar'},
{title: 'foobar', type: 'foogoo'},
];
As you can see, all elements in the array have properties starting with "foo" in either the title or the type. Also, all elements are unique, the same title and/or type can be in several elements, but the same combination of both cannot appear twice.
I want to sort this array in the following way:
- Both title and type starts with
inputVal- Type alphabetically
- Title alphabetically
- Title starts with
inputValbut not type- Type alphabetically
- Title alphabetically
- Type starts with
inputValbut not title- Type alphabetically
- Title alphabetically
The example list would be sorted as following:
const objArray = [
{title: 'foobar', type: 'foobar'}, // Criterium 1
{title: 'foohiii', type: 'foobar'}, // Criterium 1
{title: 'foobar', type: 'foogoo'}, // Criterium 1
{title: 'foobar', type: 'aaaabaa'}, // Criterium 2
{title: 'foodoo', type: 'aaaabaa'}, // Criterium 2
{title: 'foobar', type: 'moo'}, // Criterium 2
{title: 'foobar', type: 'wohoo'}, // Criterium 2
{title: 'aaah', type: 'foobar'}, // Criterium 3
{title: 'blahaa', type: 'foobar'}, // Criterium 3
{title: 'gaaaaaah', type: 'foobar'}, // Criterium 3
{title: 'aaah', type: 'foogoo'}, // Criterium 3
];
I tried using array.prototype.sort(callback) with several different callback functions, but I don't seem to get the correct one. Can anyone help me?
fooisn’t included anywhere?startsWith?aaahbelowgaaaaah? in the original order both have a different order and no rule switches them.