Prashant Singh
Prashant Singh

Reputation: 3793

Sorting string array on the basis of a match string

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

Answers (2)

Prashant Singh
Prashant Singh

Reputation: 3793

I do it finally using a number of criteria :-

  1. Individual word matching of the search result and search query
  2. Extra credits for complete matching of result and search query
  3. Portion of length of all words matching to the total length of search result
  4. Extra credits if the search query appears at an index less than half of the total length of search result
  5. A price filter for further improvements in result.

Here is the final result

Upvotes: 0

RobG
RobG

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

Related Questions