Return arrays in Javascript - javascript

I'm using the Dragsort plugin and we want to tag IDs in an array and print them.
My Html Code Is:
<ul id="list1">
<li class="ss"><div>1</div></li>
<li><div>2</div></li>
<li><div>3</div></li>
<li><div>4</div></li>
<li><div>5</div></li>
<li><div>6</div></li>
<li><div>7</div></li>
<li><div>8</div></li>
<li><div>9</div></li>
</ul>
<p id="demo"></p>
and my jQyery codes is
$("#list1, #list2").dragsort({ dragSelector: "div", dragBetween: true, dragEnd: saveOrder, placeHolderTemplate: "<li class='placeHolder'><div></div></li>" });
function saveOrder() {
var data = $("#list1 li").map(function() { return $(this).children().html(); }).get();
$("input[name=list1SortOrder]").val(data.join("|"));
};
$( "#list1 li" ).each(function( index ) {
let items = [];
items = [ index + 1];
console.log(items.map(() => index));
$(this).attr("id",items);
});
$('#hamid').click(function () {
$( "#list1 li" ).each(function() {
its = [ $(this).attr('id')];
});
});
When I want to return id <li> return last of them

You may want to change the line
its = [ $(this).attr('id')];
//this will only create an instance of an array with one element.
change the last function to something like:
$('#hamid').click(function () {
var ids = [];
$( "#list1 li" ).each(function() {
ids.push( $(this).attr('id') );
});
console.log(ids);
// this will print an array with all ids inside
// then you can return it or do whatever you want with it
});

I guess your issue is that you want to get all the IDs of the elements that matches #list1 li, as seen in the last 5 lines of your code. The reason why it is not working is because you are reassigning a brand new array to the its variable. I suggest doing one of the two:
Solution 1: Push into the array instead of reassigning it
Solution 2: Use .map() + .get() to return an array of all IDs
Solution 1 (basic)
Use Array.prototype.push() to append IDs to a pre-existing array. Remember that instead of converting this into a jQuery object and then accessing its ID via the .attr() method (by doing $(this).attr('id')), you can easily do this.id:
$('#hamid').click(function () {
var its = [];
$('#list1 li').each(function() {
its.push(this.id);
});
console.log(its);
});
Solution 2 (better)
Use a combination of .map() and .get(). This is the most jQuery-way to do it:
$('#hamid').click(function () {
var its = $('#list1 li').map(function() {
return this.id;
}).get();
console.log(its);
});
The reason why .get() is needed is because .map() returns a jQuery collection instead of an actual array. To retrieve the array itself, you will need to append .get() after .map().

Related

Returning an array of values

I need to get a list of values from a set of element attributes and store them in an array.
Currently, I am doing this:
var ids = [];
$("my selector").each(function (idx, v) {
ids.push($(v).data("id"));
});
This seems a bit clunky. Is there a more efficient/streamlined way of doing this? Perhaps something more like this:
var ids = $("my selector").data("id");
Try using .map() along with .get() in this context,
var ids = $("my selector").map(function(){
return $(this).data("id");
}).get();
Less clunky:
$("my selector").each(function () {
ids.push($(this).data("id"));
});
By, removing idx and v, you can use $(this)

I am inserting values in the array, then I am displaying that value to the textarea, in this array I need to remove duplication names?

in this SkillIds array if i found duplication name then i need to remove that names..
var SkillIds = [];
$('#SkillSets table tr :checked').each(function () {
SkillIds.push($(this).data("id"));
});
$('#textarea').val(SkillIds.tostring());
Try $.unique()
Sorts an array of DOM elements, in place, with the duplicates removed.
$('#textarea').val($.unique(SkillIds).tostring());
Or you can use $.inArray()
$('#SkillSets table tr :checked').each(function () {
var data = $(this).data("id");
if ($.inArray(data, SkillIds) === -1) {
SkillIds.push(data);
}
});
You can do the following:
var SkillIds = [];
$('#SkillSets table tr :checked').each(function () {
var id = $(this).data("id");
if( SkillIds.indexOf(id) == -1 ){//if element is not in array
SkillIds.push(id);
}
});
$('#textarea').val(SkillIds.toString());//typo here tostring() should be toString()

JQuery Selector Re-Write

I do this kind of thing all over the place, and I am looking for the most efficient (both computationally + syntactically) way to execute:
ids =[]
$('tr.selectON td').each( function() {
var answer_query = $(this).attr('id');
if ( answer_query !== undefined ) {
ids.push( answer_query )
}
});
I have access to underscore.js, which I suspect will help.
ids = $("tr.selectON td[id]").map(function() { return this.id; }).get();
Documentations :
To get elements with id attribute http://api.jquery.com/attribute-contains-prefix-selector/
To filter id attribute http://api.jquery.com/map/
To convert result into array http://api.jquery.com/get/
You can make it simpler, cant speak to the JQuery performance though:
ids =[]
$('tr.selectON td[id^=""]').each( function() {
ids.push( this.id )
});
"this" in the function is already a dom object, so you have direct access to its id.

How to create an array from .each loop with jQuery

How can I create an array from inside of the '.each loop' and use it outside of the loop?
My .each loop:
// Loop through all but button with class .apply
$('.profile-nav ul li a').not('.apply').each( function() {
// if currently loop through element has .cur class
if( $(this).hasClass('cur') ) {
//Get the first class of the match element
var ClassesToApply = $(this).prop('class').split(' ')[0];
}
//How can I create an array from all ClassesToApply?
//var arr = jQuery.makeArray(ClassesToApply);
// This will create an array, but with one element only
});
How can I create an array from all var = ClassesToApply?
And than how can I do something with this array?
e.g
$( allClasses from an array as a selectors).doStuff();
If you declare a variable outside of the each, it will be accessible inside the each:
var yourArray = [];
$('.profile-nav ul li a').not('.apply').each(function() {
if($(this).hasClass('cur')) {
yourArray.push($(this).prop('class').split(' ')[0]);
}
});
//Here, yourArray will contain the strings you require.
Although as others have shown, there are ways to shorten your code significantly.
fxnReqValidation = function () {
var InputTagArray = new Array;
InputTagArray = document.getElementsByTagName("input");
for (var iCnt = 1; iCnt <= InputTagArray.length; iCnt++) {
if ((g_Json[InputTagArray[iCnt].name].required == true) && (InputTagArray[iCnt].value == "")) {
$("#errormsg").text("please enter all required fields");
}
return false;
}
}
You could do:
var arr = $( 'a.cur:not(.apply)', '.profile-nav' ).map( function () {
return $( this ).prop( 'class' ).split( ' ' )[0];
}).get();
var list = $(".profile-nav ul li a.cur:not(.apply)");
list.each(function(){
// do your thing!
});
var arraySelectors = $('.profile-nav ul li a.cur:not(.apply)')
.toArray()
.map(e => '.' + Array.from(e.classList).join('.'));
This snippet is probably not the most elegant but it tries to accomodate to the objective the OP was describing.
I prefer not splitting a className because you never know how many consecutive spaces there is.
Exiting from the jQuery array and getting to a native array seems to be the best solution.
Array.from() is ES6 circa 2015
jQuery.toArray() appeared in jQuery 1.4

jQuery array .map inside .each

I have an array inside an $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:
// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');
$.each($selector, function() {
var $this = $(this), // cache selector
keys = ['my0', 'my1', 'my2']; // array of data keys
// I want to use the keys array to make a vals array to this:
// var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];
// This doesn't seem to work (can't read from length 0 error):
var vals = $.map( keys, function( key ) { return $this.data(key); });
});
I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.
Wait - you're passing "vals" into your "$.map()" cal instead of "keys":
var vals = $.map( keys, function( key ) { return $this.data(key); });
Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.

Categories