LinQ foreach in javascript / jquery
How can I easily do these types 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 one
foreach (var i in DbList2)
{
a += i.FieldB + ", ";
}
Loop number 2 can be solved like this at least.
$.each(aData.DbList2, function (index, value) {
a += value.FieldB;
);
Not 100% sure if this is the most effective though
+3
source to share
2 answers
The second is easy enough to do in vanilla JavaScript:
var a = "";
for (var i = 0; i < DbList2.length; i++){
a += DbList2[i].FieldB + ", ";
}
A little bit tricky at first 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 + ", ";
}
}
+2
source to share
You can use the map method to iterate over an array variable.
Snippets of code:
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);
});
+3
source to share