I need to sort a javascript array within the search result with the keyword which we searched. For example:
var profile = [
{name: 'Arjun', age: 10},
{name: 'Manu', age: 12},
{name: 'Lipin', age: 15},
{name: 'Anu', age: 11},
{name: 'Anupama', age: 21},
{name: 'Jijo', age: 34}
];
And If the keyword to be searched is "Anu". I want the result as follows.
[
{name: 'Anu', age: 11},
{name: 'Anupama', age: 21},
{name: 'Manu', age: 12}
]
That is, I need to filter the array and sort the result with the keyword.
Following is the code I have tried. The search is working fine. How can I filter with the search keyword?
var profile = [
{name: 'Arjun', age: 10},
{name: 'Manu', age: 12},
{name: 'Lipin', age: 15},
{name: 'Anu', age: 11},
{name: 'Anupama', age: 21},
{name: 'Jijo', age: 34},
{name: 'Abhiram', age: 22},
{name: 'Ram', age: 20},
{name: 'Ram Gopal', age: 21},
{name: 'Ramachandran', age: 20},
{name: 'Sreeram', age: 19},
];
beneficiaryname = "Anu";
result = profile.map(function(item, index){
var existingname = 1;
var row_ben_name = item.name;
existingname = row_ben_name.toLowerCase().search(beneficiaryname.toLowerCase()) !== -1;
if (existingname){
return item;
}
});
result = result.filter(function( element ) {
return element !== undefined;
});
console.log(result);
NOTE: I want to sort the array with the search keyword. Not as default A-Z sorting.
UPDATE:
For More Clarity, I have updated my question with more data and expected results.
If I search with another keyword "Ram". I need the following result.
[
{name: 'Ram', age: 20},
{name: "Ram Gopal", age: 21},
{name: "Ramachandran", age: 20},
{name: "Abhiram", age: 22},
{name: "Sreeram", age: 19}
]
See the above-expected result is sorted with the keyword searched. That is, In the sorted result, First we need to sort the exact search result, then keyword as first in string, then anywhere inside, then at the end of the string. I hope everyone got the problem.
profile.filter(x=>x.name.toLowerCase().contains("anu")).sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));