1

I am trying to sort the given array by the property "title"

how can I sort it? please help on how can I solve it. thanks.

data = [
{
  _index: 'yo',
  _type: 'sample1',
  _id: '201',
  _score: null,
  _source: {
    type: 'digi',
    title: 'The Happy',
    description: 'san',
    image: 'good.jpg',
  },
  sort: [ sam ]
},
{
    _index: 'ya',
    _type: 'sample2',
    _id: '201',
    _score: null,
    _source: {
      type: 'sam',
      title: 'The lonely',
      description: 'san',
      image: 'y.jpg',
    },
    sort: [ sam ]
  },
  {
    _index: 'yi',
    _type: 'sample3',
    _id: '201',
    _score: null,
    _source: {
      type: 'sam',
      title: 'The Angry',
      description: 'sam',
      image: 'x.jpg',
    },
    sort: [ sam ]
  }
]

thanks

this is what I am trying

data.sort(function (x, y) {
    let a = x._source.title.toUpperCase(),
        b = y._source.title.toUpperCase();
    return a == b ? 0 : a > b ? 1 : -1;
});

console.console(data);

But i am failing to access title.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • `But i am failing to access title` what do you mean by this exactly? What are you getting right now, and what do you want it to return exactly? – C. Peck May 14 '21 at 10:00
  • 1
    A [mcve] of your code works as expected: https://jsfiddle.net/h3jkceam/ – Andreas May 14 '21 at 10:05
  • Please make this an actual [mcve] that shows the described behavior and explain the problem you have (_"But i am failing to access title"_ is not enough) -> [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas May 14 '21 at 10:07
  • or try with `localeCompare()`: `data.sort((a,b) => a._source.title.toLowerCase().localeCompare(b._source.title.toLowerCase())) ` – boxdox May 14 '21 at 10:08
  • @boxdox What does this change? OPs script works. And in case OP really struggles to get the content of the `title` property then your approach would also not work. And also there are better options for a [case-insensitive comparison](https://stackoverflow.com/questions/34861386/force-localecompare-to-be-case-sensitive) – Andreas May 14 '21 at 10:23

0 Answers0