0

I'm getting success result in my ajax code and can return data in my view but i want to sort the results by their id in database,

Example

id => 3 , one
id => 5 , three
id => 2 , five

result should be:

five
one
three

Code

<script defer>
  $(document).ready(function() {
    $('select[name="selectset"]').on('change', function() {
      var id = $(this).val();
      if(id) {
      $.ajax({
        url: '{{ url('admin/selectset') }}/'+encodeURI(id),
        type: "GET",
        dataType: "json",
        success:function(result) {

          $.each(result, function(key1, value1) {

            var vvvid = value1.id;

            // second data
            $.ajax({
              url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
              type: "GET",
              dataType: "json",
              success:function(data) {
                var my_row = $('<div class="row mt-20 ccin">');
                    var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
                    my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
                    my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
                    my_row.html(my_html);
                    $('div#dataaa').append(my_row);
              }
            });
            // second data

          });
        }
      });
      }else{
        $('div#dataaa').empty();
      }
    });
  });
</script>

PS: what I need is to return vvvid part by their id in database.

one

Question

  1. How can I sort my output data?
mafortis
  • 6,750
  • 23
  • 130
  • 288

2 Answers2

1

Sort your result by the id in a one-liner shameless lifted from this answer.

Then $.each() it.

 success:function(result) {

   result.sort(function(a,b) {
    return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
   });

   // console.log(result);

   $.each(result, function(key1, value1) {
ourmandave
  • 1,505
  • 2
  • 15
  • 49
0

I believe that your ID is in your object like it

{
    id: 1,
    title: sample
}

Make a function like it

static compare(a,b) {
        if (a.id > b.id)
            return -1;
        if (a.id < b.id)
            return 1;
        return 0;
    }

Using

let array = [{},{},{}];
array.sort(this.compare);

To change the order by, just reverse > and < in the function

guiCunha
  • 343
  • 1
  • 4