-4

I'm trying to sort an array of objects according to position of a 'restaurant' string in title field

var test = [{
    title: 'Roy Restaurant'
  },
  {
    title: 'Restaurant'
  },
  {
    title: 'Roy Mega Restaurant'
  }
];

console.log(test.sort(function(a, b) {
  return a.title.toLowerCase().indexOf('restaurant') > b.title.toLowerCase().indexOf('restaurant');
}));

so what my expected output is

var test = [
    {
    title : 'Restaurant'
  },
  {
    title : 'Roy Restaurant'
  },
  {
    title : 'Roy Mega Restaurant'
  }
];

so rank them by their indexOf value. Above, the first item indexOf value is 0 so it must be the first item, 2nd Roy Restaurant because the word occurence is less than from the 3rd item.

Any help, ideas please?

Nick
  • 138,499
  • 22
  • 57
  • 95
Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • 2
    what is the problem? Run the code and confirm if it is working as expected – brk Jan 15 '19 at 06:14
  • 1
    You forget to ask a question. What do you need help with? – Lie Ryan Jan 15 '19 at 06:15
  • @Teemu I misinterpreted question. I thought we have to sort alphabetically. Hence marked it dupe but was about to retract vote as we have to sort based on index position. Though, I'm still confused as to what OP is looking for. Code provided works fine – Rajesh Jan 15 '19 at 06:25

1 Answers1

0

The sort comparisons wants an integer not a bool. From MDN

If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).

Change > to - on line 14.

var test = [
    {
    title : 'Roy Restaurant'
  },
  {
    title : 'Restaurant'
  },
  {
    title : 'Roy Mega Restaurant'
  }
];

console.log( test.sort(function(a,b){
    return a.title.toLowerCase().indexOf('restaurant') - b.title.toLowerCase().indexOf('restaurant');
}) );
Trobol
  • 1,210
  • 9
  • 12