Reputation: 3793
I have a JSON object containing a number of strings. I also have a match string . Now I wish to arrange the object of strings on the basis of how closely (more) they match with match string.
How this can be done using Javascript.
Suppose, I searched for Philips SHM6110U Headphone
Search will then fetch following result.
[
{
"position": 12,
"link": "http:\/\/www.talash.com\/buy-online-philips-shl5001-hi-fi-headphone-headband-headphone-india-product.html",
"image": "http:\/\/staticus.talash.com\/product_images\/p\/092\/DM1573_1lg__52708_thumb.jpg",
"prod": "Philips Shl5001 Hi Fi Headphone Headband Headphone",
"price": "Rs. 1000"
},
{
"position": 12,
"link": "http:\/\/www.talash.com\/buy-online-philips-shl5000-hi-fi-headphone-headband-headphone-india-product.html",
"image": "http:\/\/staticus.talash.com\/product_images\/n\/497\/DM1572_1lg__57945_thumb.jpg",
"prod": "Philips Shl5000 Hi Fi Headphone Headband Headphone",
"price": "Rs. 1030"
}
]
Now, I have to sort them according to the match string "Philips SHM6110U Headphone" and the prod
value of JSON.
Suggesting an algorithm or sample source code will do!
Upvotes: 0
Views: 218
Reputation: 3793
I do it finally using a number of criteria :-
Here is the final result
Upvotes: 0
Reputation: 147493
You can pass a comparison function to Array.prototype.sort.
var results = [
{"position": 12,
...
"prod": "Philips Shl5001 Hi Fi Headphone Headband Headphone",
...
},
{"position": 12,
...
"prod": "Philips Shl5000 Hi Fi Headphone Headband Headphone",
...
}
];
results.sort(function(a, b) {
return a.prod < b.prod? -1 : a.prod == b.prod? 0 : 1;
});
The result will be the array sorted by obj.prod values.
Upvotes: 2