最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sort array with a search keyword - Javascript - Stack Overflow

programmeradmin5浏览0评论

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

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.

Share Improve this question edited Jan 10, 2020 at 5:33 Adharsh M asked Jan 10, 2020 at 4:42 Adharsh MAdharsh M 2,8123 gold badges22 silver badges35 bronze badges 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)); – Sourabh Somani Commented Jan 10, 2020 at 4:54
  • This is almost same except it doesn't filter out results. stackoverflow./questions/26796276/… – sanister Commented Jun 30, 2020 at 13:52
Add a ment  | 

4 Answers 4

Reset to default 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);

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

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)

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

发布评论

评论列表(0)

  1. 暂无评论