Home > Enterprise >  Rearrange the array based on the values in javascript & executing for loop
Rearrange the array based on the values in javascript & executing for loop

Time:11-08

Please see my js function below. Inside the display_data function, I call the show_product_block function to show individual product blocks.

var item =[];
function display_data(sort_value){
    var my_data = get_data();
    var item_price;
    if (my_data != null) {
        for (i = 0; i < my_data.length; i  ) {
                var item_name = my_data[i].name;
                var item_qty = my_data[i].qty;
                var item_price = get_price(my_data[i].innder_id);
                item[i] = item_name  '-'  item_qty  '-'  item_price;
                show_product_block(item_name, item_qty,item_price);
        }
            
    }
}

Here I need to call the show_product_block based on price low to high, high to low, and most quantity required. I have a dropdown menu with values default, price_low,price_high, and most_qty. Now somebody changes the dropdown value to most_qty; then I have to call show_product_block based on the most quantity needed. So I modified the function like this.

var item =[];
function display_data(sort_value){
    var my_data = get_data();
    var item_price;
    if (my_data != null) {
        for (i = 0; i < my_data.length; i  ) {
                var item_name = my_data[i].name;
                var item_qty = my_data[i].qty;
                var item_price = get_price(my_data[i].innder_id);
                item[i] = item_name  '-'  item_qty  '-'  item_price;
                if (sort_value == 'default') {
                    show_product_block(item_name, item_qty,item_price);
                }
        }
        
        if (sort_value == 'most_qty'){
            *Here from the item array, I have to take the product
            based on item_qty and then call show_product_block 
            inside a for loop.* 
        }
            
    }
}

Please help me to solve this.

CodePudding user response:

Consider the following.

$(function() {
  var myData = [{
    name: "Item 1",
    qty: 3,
    innder_id: 1001
  }, {
    name: "Item 5",
    qty: 2,
    innder_id: 1002
  }, {
    name: "Item 3",
    qty: 1,
    innder_id: 1003
  }];

  function obj_sort(o, i) {
    // Input: Object, Index
    // Output: Sorted Object by Index
    if (o == undefined) {
      // Object is undefined, exit
      console.log("Object Undefined");
      return false;
    }
    // Collect object keys
    var k = Object.keys(o[0]);
    if (i === undefined) {
      // If Index is undefined, set to first Key
      i = k[0];
    }
    if (typeof i === "number" && i < k.length) {
      // If Index is a number and in range, select proper Key
      i = k[i];
    } else {
      console.log(i);
      return -1;
    }
    if (k.indexOf(i) === -1) {
      console.log(i   " is not in Range");
      return -1;
    }
    // Sort the Object by Index
    o = o.sort(function(a, b) {
      // Check for Number Sort
      if (typeof a[i] === "number") {
        return a[i] - b[i];
      }
      // Text Sort
      if (a[i] < b[i]) {
        return -1;
      }
      if (a[i] > b[i]) {
        return 1;
      }
      return 0;
    });
    // Return the sorted Object
    return o;
  }

  function showData(o, t) {
    console.log("Show Data: "   o.length   " Rows");
    $("tbody", t).html("");
    $.each(o, function(i, row) {
      var tr = $("<tr>").appendTo($("tbody", t));
      $.each(row, function(j, cell) {
        $("<td>").html(cell).appendTo(tr);
      });
    });
  }

  showData(myData, $(".table-wrapper table"));

  $("table thead th").click(function() {
    myData = obj_sort(myData, $(this).index());
    showData(myData, $(".table-wrapper table"));
  });
});
.table-wrapper table {
  width: 100%;
}

.table-wrapper table thead th {
  cursor: pointer;
}

.table-wrapper table tbody td {
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Quantity</th>
        <th>Price</th>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>

You can use Sort, yet you need a comparison function.

Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

I've provided an example of a highly dynamic sort function. You pass in an Object, and, optionally, an Index as parameters. It will return an object that is sorted.

This example allows you to click the headers to sort by that column. It will always default to an ascending sort order.

  • Related