2

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.

2
  • Do this profile.filter(x=>x.name.toLowerCase().contains("anu")).sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)); Commented Jan 10, 2020 at 4:54
  • This is almost same except it doesn't filter out results. stackoverflow.com/questions/26796276/… Commented Jun 30, 2020 at 13:52

4 Answers 4

10

You can achieve same by writing code as follows

I have updated the code after more clarifications in your question

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},
    ];

let keyword = 'Ram';

let search_results = profile
    .filter(prof => {
        // Filter results by doing case insensitive match on name here
        return prof.name.toLowerCase().includes(keyword.toLowerCase());
    })
    .sort((a, b) => {
        // Sort results by matching name with keyword position in name
        if(a.name.toLowerCase().indexOf(keyword.toLowerCase()) > b.name.toLowerCase().indexOf(keyword.toLowerCase())) {
            return 1;
        } else if (a.name.toLowerCase().indexOf(keyword.toLowerCase()) < b.name.toLowerCase().indexOf(keyword.toLowerCase())) {
            return -1;
        } else {
            if(a.name > b.name)
                return 1;
            else
                return -1;
        }
    });

console.log(search_results);

Sign up to request clarification or add additional context in comments.

4 Comments

This is default sorting with a sort function as (A - Z). I want to sort the array with the search keyword.
Check this one now, I have updated the code as you suggested
Thanks. That's what I exactly need.
Great! Please mark this one as accepted answer, so everyone looking for similar issue can refer to same.
4

Use decorate-sort-undecorate to create an array that includes the string you wish to sort by for each object. Then you sort using the key. Afterwards you extract the object from that array.

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}, ],
  keyword = 'Ram',
  matchWord = keyword.toLowerCase(),
  result = profile
              .map(o => [o.name.toLowerCase(),o])
              .filter(([name]) => name.includes(matchWord))
              .sort(([a], [b]) => a.indexOf(matchWord) - b.indexOf(matchWord))
              .map(([,o]) => o);

console.log(result);

You can array#filter on the name and then lexicographical sort it using array#sort on your 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}, ],
  keyword = 'Ram',
  result = profile.filter(o => o.name.toLowerCase().includes(keyword.toLowerCase()))
                  .sort((a, b) => a.name.toLowerCase().indexOf(keyword.toLowerCase()) - b.name.toLowerCase().indexOf(keyword.toLowerCase()));

console.log(result);

2 Comments

But I need to sort the array with searched keyword.
This is by far the cleanest solution
2

let prof = [{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}]

srch = "Ram"

let res = prof.filter(el => new RegExp(srch,"ig").test(el.name)).sort((a,b) => {
    let re = new RegExp("^"+srch, "i")
    return re.test(a.name) ? re.test(b.name) ? a.name.localeCompare(b.name) : -1 : 1
})

console.log(res)

3 Comments

This is the default sorting with a sort function as (A - Z). I want to sort the array with the search keyword.
@AdhershMNair it's sorted according to your example. I guess I don't understand what you mean.
I will update the question with more expected results. I need to sort the answer with the keyword.
2

Can you try the below code, I have added for sorting section only

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 = "Ram";
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);

result.sort((a,b) => {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
var an = a.indexOf(beneficiaryname.toLowerCase());
var bn = b.indexOf(beneficiaryname.toLowerCase());
//console.log(an);console.log(bn);
if(an === bn)
  return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);
else
  return  an > bn ? 1 : -1;

  }); 
  console.log(result);

5 Comments

This is default sorting with a sort function as (A - Z). I want to sort the array with the search keyword.
@AdhershMNair Can you explain with an example or sample data in your question ?
Sure. I will update the question with more data and the expected result.
Updated my question.
@AdhershMNair Updated my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.