Loop through array and match items to html elements - javascript

I am looking for a more intuitive way to run the code below (as it is also incomplete to my purpose).
for (j = 0; j<items.length; j++) {
var indivItem = items[j];
if (indivItem.category == 1) {
$('.indiv_category[idnumber="1"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}
else if (indivItem.category == 2) {
$('.indiv_category[idnumber="2"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}
}
Essentially I need line 3 to check if (indivItem.category > 0) then look for the element with a matching idnumber attribute and append the necessary info.
I need this continue for the length of available .indiv_category elements.
Basically a matchup of the all items in the 'items' array to all of the elements with a matching 'idnumber' attribute to the item in the array that contains the same id number.

Remmove the condition and just use the variable items[j].category in selector.
for (j = 0; j<items.length; j++) {
$('.indiv_category[idnumber="'+ items[j].category + '"]').append('<ul class="left_side_item"><li>'+indivItem.title+'</li></ul>');
}

Related

Check inside a loop that array has next element in Javascript/QML

I have an array items. I need to make sure that in the current iteration of the loop I can safely call the next item of the array
for(var i = 0; i < items.length; ++i) {
// do some stuff with current index e.g....
item = items[i];
// then do something with item # i+1
if(items[i+1]) {
//do stuff
}
}
Is this how it is done or if not how/what would be the better way?
P.S. I do not want to do a bound check
If you want to loop through every element except the last one (which doesn't have an element after it), you should do as suggested:
for(var i = 0; i < items.length-1; ++i) {
// items[i+1] will always exist inside this loop
}
If, however, you want to loop through every element -even the last one-, and just add a condition if there is an element after, just move that same condition inside your loop:
for(var i = 0; i < items.length; ++i) {
// do stuff on every element
if(i < items.length-1){
// items[i+1] will always exist inside this condition
}
}
if(items[i+1]) will return false (and not execute the condition) if the next element contains a falsey value like false, 0, "" (an empty String returns false).
Put a value check on variable i and make sure it is less than items.length-1 in order to safely access items[i+1].
for(var i = 0; i < items.length-1; ++i) {
if(items[i+1]) {
//do stuff
}
}
Drop the for loop and use array#forEach, and simply check whether a next value exists:
items.forEach(function (item, index) {
if (!items[index + 1]) return;
// do something with item and items[index + 1]
});

javascript : after calling the splice() control comes out from the loop

I have an array rosters and i want to alter this array according to some conditions. Here what I'm trying to do.
somefunction(callback) {
for (var i in this.rosters) {
var roster = this.rosters[i];
if (roster.age > 7200) {
this.rosters.splice(i, 1);
} else {
this.rosters[i].age = this.EMarshal.tu.getAgeOfTime(
this.EMarshal.tu.getMyTime(
this.EMarshal.tu.getMyDate(roster.date), roster.shifttime
)
);
console.log(this.rosters[i].age);
}
}
callback();
}
When the the if condition is true and splice is been called, control comes out of from loop and call callback(). But i want to run the loop for each values in the array.
plz carefully notice that there are rosters and roster 2 different variables.
Any idea why its happening and the solution will be usefull.
Thanks
It's just because you are trying to alter the array on which you are iterating.
So, just ad some logic to store the indexes as you have said you have tried.
Here is one suggestion
before getting into loop var index = [];
then your if condition
if (roster.age > 7200) {
index.push(i);
}
and then after the loop, remove those indexes from rosters
for (var j = index.length - 1; j > -1; j-- ) {
console.log(j);
this.rosters.splice(index[j], 1);
}
Remember to iterate the index from last index otherwise you will remove the 1st index and the trying to remove the last index from the rosters, but now you have removed the element from the array so the length is been changed.

deleting an item from array and add it to another array

I'm trying to delete an item from an array and add it to another array. The array states consists of a list of 50 states. User needs to enter the name of a state and the state must get deleted from states array and get added to the array correctState. Here is my code
function searchString()
{
var total = 50;
var string = document.getElementById("txtState").value;
var element = document.getElementById("status");
for (i=0; i < states.length; i++)
{
if(states[i].toUpperCase() == string.toUpperCase())
{
count = count + 1;
//element.innerHTML = "CORRECT!!!"
addElem = states.splice(i,1);
correctState.push(addElem);
/*for (j=0; j < correctState.length; j++)
{
if(correctState[j].toUpperCase() == string.toUpperCase())
{
element.innerHTML = "Already Submitted. Try another State";
}
}*/
}
document.getElementById("score").innerHTML = count +"/"+ total;
document.write(states);
document.write(correctState);
}
}
Enter State : <input type="text" name="txtState" id="txtState"><span id="timer"></span><br /><span id="status"></span>
<button type="button" name="btnPlay" id="btnPlay" accesskey="s" onClick="searchString()"><u>S</u>ubmit</button>
I'm not able to achieve what I need. I'm new to javascript and need help.
Re these lines:
addElem = states.splice(i,1);
correctState.push(addElem);
splice doesn't return the element that you remove, it returns an array of those elements. So your code is pushing array instances onto correctState. I'd do this:
correctState.push(states[i]); // First push the matching state onto `correctStates`
states.splice(i,1); // ...then remove it
Alternately, you could do it in the order you showed, you just have to get the removed element out of the array you get back
addElem = states.splice(i,1);
correctState.push(addElem[0]);
// Here -----------------^^^
but again, I'd do it by pushing first, then removing.
Separately, I'd use the debugger built into your browser to single-step through that code and watch it run. I suspect you'll find that you want to move some things around, and you almost certainly want to stop looping once you've found that string matches something in the array.
My guess is that it's the fact that you're modifying your states array while you are still enumerating.
So say you're states array is [AR, LA, CT] and the user entered LA. So your for loop goes like this
i = 0 (length is 3 so i < 3)
string not found
i = 1 (length is 3 so i < 3)
string found, remove it from states
i = 2 (length is 2 so i < 2 fails and there's no final loop)
What you probably want is just something like this
function moveAllInstancesBetweenArrays(val, source, destination) {
var indexOfVal = source.map(function(s) { return s.toUpperCase() })
.indexOf(val.toUpperCase());
if(indexOfVal == -1)
return;
source.splice(indexOfVal, 1);
destination.push(val);
moveAllInstancesBetweenArrays(val, source, destination); //continue until all matching are moved
}
moveAllInstancesBetweenArrays(yourSearchVal, states, correctStates);

cross browser remove element from an array

I have an array of numbers which are values of the data-cardNumber attribute of different element in my site.
I'm trying to remove the value of the data-cardNumber attribute of the element that has that attribute that also has the class .lastBeenDragged.
I am trying this, but I think I may have oversimplified my code too much.
When I console.log the array before and after executing this code there is no change in the array.
How can I properly and cross browserly remove an element, the value of the data-cardNumber of the element with the class .lastBeen Dragged, from the array swipedAwayCards ?
Here is the code:
if(swipedAwayCards.indexOf($('.lastCardDragged').attr('data-cardNumber')) > -1) swipedAwayCards.splice(swipedAwayCards.indexOf($('.lastCardDragged').attr('data-cardNumber')), 1);
Since Array.indexOf() is not supported crossbrowser, you can user $.inArray()
var index = $.inArray($('.lastCardDragged').attr('data-cardNumber'), swipedAwayCards);
if (index > -1) {
swipedAwayCards.splice(index, 1);
}
Try this :
var v = $('.lastCardDragged').attr('data-cardNumber');
for (var i = 0, l = swipedAwayCards.length; i < l; i++) {
if (swipedAwayCards[i] == v) {
swipedAwayCards.splice(i, 1);
break;
}
}

Handling Duplicate objects in Javascript

I have a javascript method which handles removing from one select box to another.
The code runs as follows :
function moveAllOptions(formName, selectId1, selectId2) {
var sourceSelect = eval("document." + formName + "." + selectId1);
var destSelect = eval("document." + formName + "." + selectId2);
for (var i = 0; i < sourceSelect.length; i++) {
var optionText = sourceSelect.options[i].text;
var optionValue = sourceSelect.options[i].value;
for (var j = 0; j < destSelect.length; j++) {
if (destSelect.options[j].value == optionValue) {
destSelect.options[j].value = null;
}
}
}
}
But I found a problem like when it encounters duplicate values it is not deleting all the values .For eg: in the view source I have
value="139">Customer Service<
value="231">Customer Service<
value="231">Customer Service<
value="231">Customer Service<
value="231">Customer Service<
In this case it removes only two objects from my left hand box.
Is there any way to remove duplicate objects also.One way I could think is create an two array objects(Two Dimensional), pass all the values in left hand side to one array then iterate to another array and finally pass again to normal options.
Well, first of all the eval to hunt elements is horrible. There are far better ways of doing this starting with getElementById.
As to your actual problem, again there are simpler native ways to do this: the add and remove methods of the select object (reference). Try this method to start with.
function transferOptions(A, B)
{
var a = document.getElementById(A);
var b = document.getElementById(B);
while(a.options.length)
{
var x = a.options[0]; //store the value
a.remove(0); //remove it from the DOM
b.add(x); //reinsert it (adds to end of list)
}
}
transferOptions('select1','select2') //usage
for (var j = 0; j < destSelect.length; j++) {
if (destSelect.options[j].value == optionValue) {
destSelect.options[j].value = null;
}
}
Let's say the first item matched. You set destSelect.options[0].value to null, which effectively removes the first option from the list. Next you check destSelect.options[1], which is actually the third option in the original list. The second option has just become first, and occupies destSelect.options[0].
The way to avoid this problem is to go backwards, starting with the last item in the list and working up to the first.
for (var j = destSelect.length-1; j >=0; j--) {
if (destSelect.options[j].value == optionValue) {
destSelect.options[j].value = null;
}
}

Categories

Resources