2017-01-22 83 views
0

我有下面的代码,它查看类howmanyproducts的隐藏输入。Javascript将输入值排序到数组

$("#proddiv .howmanyproducts").each(function() { 
    var idval = $(this.id).val(); 
}); 

我想实现是每个ID获得的价值和IDS分类基于其值的数组。

回答

0

你必须到这两个ID和相应的值添加到一个数组,然后使用您的阵列的sort方法与适应比较功能。让说,你的价值观是数量,但取出作为字符串:

// Create a new empty array : 
    var ids = []; 
    $("#proddiv .howmanyproducts").each(function() { 
     var id = this.id; 
     var val = $(this.id).val(); 
     // Store the id and the value: 
     ids.push([id, +val]); 
    }); 
    // Sort the array in place, using the second element of each item 
    // ie. the value : 
    ids.sort(function(a, b) { return a[1] - b[1]; }); 
    // Once sorted, make a new array with only the ids: 
    var result = ids.map(function(a,b) { return a[0] }); 

我用的是传统的语法,但请注意,它可以写成更简单地使用箭头功能:

ids.sort((a,b) => a[1] - b[1]); 
var result = ids.map((a,b) => a[0]); 
+0

我需要显示的ID在数组中而不是他们的值,但排序需要在值。它是否需要多维? –

+0

是的,你可以在多维数组上使用它,我更新了我的答案。 – mgc

0
var arrayOfValues = []; 

$("#proddiv .howmanyproducts").each(function() { 
    arrayOfValues.push($(this).val()); 
}