5

How can I easily do these type of loops in Jquery or Javascript? Preferably without any other plugins.

string a = "";
foreach (var i in (from a in DbList1 select a.FieldA).Distinct())
{
   a += i + ", ";
}

and this

foreach (var i in DbList2)
{
   a += i.FieldB + ", ";
}

Loop number 2 could be solved like this atleast.

$.each(aData.DbList2, function (index, value) {
 a += value.FieldB;
);

Not 100% sure this is the most effective though

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
stibay
  • 1,200
  • 6
  • 23
  • 44
  • 2
    are you iterating upon an array and getting something from each element ? Better to post a sample question like **How to concatinate words in array ?** Syntax from other languages are just confusing. – Mritunjay Jul 10 '15 at 11:36
  • In the javascript, its an array inside a object – stibay Jul 10 '15 at 11:37
  • hi please find this URL that may be help to you http://stackoverflow.com/questions/11887450/each-vs-for-loop-and-performance – Neo Vijay Jul 10 '15 at 11:43
  • a sample of your source data would go a long way to getting help on how to do something with it - I take it, since you don't want any libraries (except the biggest piece of bloat in existence, jQueery) https://linqjs.codeplex.com/ is out of the question – Jaromanda X Jul 10 '15 at 11:44

2 Answers2

3

You can use map method for iterating array variable.

Code snippets:

var arr = jQuery.map( aData.DbList2, function(value) {
return value.FieldB;
});
//To get unique array variable
var uniqueArr = [];
$.each(arr, function (i, el) {
            if ($.inArray(el, uniqueArr) === -1) uniqueArr.push(el);
        });
John R
  • 2,741
  • 2
  • 13
  • 32
2

Second one is easy enough to do in vanilla JavaScript:

var a = "";
for (var i = 0; i < DbList2.length; i++){
    a += DbList2[i].FieldB + ", ";
}

First one is a little trickier, but not impossible and can also be done with vanilla JS.

var a = "";
var uniques = [];

for (var i = 0; i < DbList1.length; i++ ){
    var fieldA = DbList1[i].FieldA;
    // check if we've already seen this value
    if (uniques.indexOf(fieldA) < 0)
    {
        // Nope, record it for future use
        uniques.push(fieldA)

        // and update the string.
        a += fieldA + ", ";
    }
}
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • According to http://stackoverflow.com/questions/11887450/each-vs-for-loop-and-performance this seems to be very good performace. So is it an easy way to only add unique values to a? – stibay Jul 10 '15 at 12:02