0

I have an array of objects with many layers. It looks like this:

var array = [
  {
    fields: { title: "Some title here" },
    sys: { id: "1234" }
  },
  {
    fields: { title: "Another one there" },
    sys: { id: "13456" }
  },
  {
    fields: { title: "Final example" },
    sys: { id: "234" }
  },
  {
    fields: { title: "Most final thing" },
    sys: { id: "4665" }
  },
];

Now I want to sort the array based on whether text exists in the fields.title. For example, I have the phrase "Final search". That needs to sort the array so the current array[2] and array[3] move to the top positions because they contain the word "final".

The sort needs to include multiple words though. So if I used the phrase "final example", array[2] would go first because it contains both words, followed by array[3] which only contains "final".

Is this possible and how?

8
  • 1
    Yes, it is possible. Commented May 4, 2015 at 16:07
  • Check out the sort method. Commented May 4, 2015 at 16:09
  • @MikeC thanks. I already knew about sort but have never seen it used like this before with multiple sort queries and on a multi level array. Commented May 4, 2015 at 16:10
  • 3
    It's all about how you write your compare function. That will depend a lot on your specific needs. Commented May 4, 2015 at 16:13
  • 1
    Js arrays are zero-indexed, so in your example you don't have array[4]. Also you should clarify which text you want to check (probably fields.title), so pls edit your question to be more concise. Commented May 4, 2015 at 16:14

2 Answers 2

1

Yes, it is possible.

You could split the strings by space character, count the intersection of the 2 generated arrays and use it for sorting. Another option which follows the same logic and should be faster is using regular expression and String.prototype.match method, something like:

function finder(input) {
    var reg = new RegExp(input.trim().split(' ').join('|'), 'gi');
    return function(el) {
       var m = el.fields.title.match(reg);
       return m ? m.length : -1;
    }         
}

function sortBy(arr, input) {
    var find = finder(input);
    return arr.sort(function (a, b) {
        return find(a) < find(b);
    });
}

sortBy(array, "user input");

Here is a demo.

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

Comments

0

What you're describing is a little more complicated than the title suggests - you're probably better of using a small text search and ranking library like Twitter's Bloodhound.

Comments

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.