2017-01-22 56 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()); 
}