简体   繁体   中英

Sorting multidimensional js array

SUGGESTED DUPLICATE ANSWER DOES NOT SOLVE

I have 4 hidden inputs where the value increments based on user actions. Var Id gets the id of each input value and var val its value.

<input class="howmanyproducts" id="<?php echo $value; ?>" name="<?php echo $value; ?>" type="hidden" value="0">

I push each set of values into an array which will output:

8(id), 1(val) 
9, 2 
3, 5 
7, 8

I need to sort these values based on the val. So the above should return:

7, 8
3, 5
9, 2
8, 1

Below is what I have so far, hope the question makes sense!

$("#proddiv .howmanyproducts").each(function() {
    var id = this.id;
    var val = $(this).val();
    ids.push([id, +val]);
 });

    ids.sort(function(b, a) { return a[1] - b[1]; });
    $("#productorder").val(ids);
    $("#productscore").submit();

Below is how I retrieve the form data which needs to be in sorted

 $prodorder = $_POST['productorder'];
 $array2 = array_unique(explode(',', $prodorder));

My current code is not changing the order at all!

item, then form will submit. I think this is your problem, I tested you sort function and it is true:

 var arr = [];
    arr.push([1, 3]);
    arr.push([2, 2]);
    arr.push([4, 8]);
    arr.push([0, 9]);
    arr.sort(function (b, a) { return a[1] - b[1]; });
    console.log(arr);

I believe you want to sort an array of objects with id and val properties by descending order of the val values, is that correct? If that's the case then sort will do what you need:

let A = [{id: 8, val: 1}, {id: 9, val: 2}, {id: 3, val: 5}, {id: 7, val: 8}]
A.sort((a, b) => a.val < b.val)
[{id: 7, val: 8}, {id: 3, val: 5}, {id: 9, val: 2}, {id: 8, val: 1}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM