开发者

How to separate a List into two Lists

开发者 https://www.devze.com 2023-03-07 11:00 出处:网络
In my form, I have multiple fields (hidden text boxes) which has the same name (eform_id). (For example I have 7 hidden textboxes which contains values like this 1234,-1235,1236,1237,-1238,-1239,1240)

In my form, I have multiple fields (hidden text boxes) which has the same name (eform_id). (For example I have 7 hidden textboxes which contains values like this 1234,-1235,1236,1237,-1238,-1239,1240).

I am getting those values to my js file like this.

var eformDetailIds=$("[name=eform_id]").map(function(){
    return $(this).val() }).get();

Now my requirement is I have to开发者_如何学Go separate this eformDetailIds into two lists..(or a string of comma separated values) so that first list contains all positive values and second list contains all negative values.

Please help me with suitable code which resolves my problem.


Well:

var positives = $.map(eformDetailIds, function(e) { return e >= 0 ? e : null; });
var negatives = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

If you return null from the ".map()" callback, then nothing is added to the result array.

You could also do this with a simple(r) for loop:

var positives = [], negatives = [];
for (var i = 0; i < eformDetailIds.length; ++i)
  if (eformDetailIds[i] >= 0)
    positives.push(eformDetailIds[i]);
  else
    negatives.push(eformDetailIds[i]);
}

If you want a comma-separated string form, just call ".join()" on the array:

var strsPositive = positive.join(',');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号