Looping through objects in an array JS - javascript

I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.
I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.
The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].
var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");
var changeWtime = setInterval(function () {
for (x; x < 1; x++) {
return x;
while (x > i) {
adsArr[1].css("display", "block");
}
};
}, 5000);
console.log(x);
changeWtime;
I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.

Issues with your code
You're creating a double array when you push elements into 'adsArr':
adsArr.push(elements);
You're throwing a return statement in the for loop:
for (x; x < 1; x++ ){
return x;
// ...
You have a double loop for no reason while inside of the for.
Solution
I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:
var miniAds = $('#mini_ads'),
elements = miniAds.children(),
i = 2,
x = 0;
elements.hide();
var changeWtime = setInterval(function () {
if ( x < i ) {
$(elements[x]).show();
}
x++;
}, 5000);
Link to example on jsbin.

Hi u should push child divs as below function does and after that i believe u can perform ur task...
var adsArr= [];
$('#mini_ads').children().each(
function(i){
adsArr.push(this);
});

In plain Javascript use .styles()
.css() which is a JQuery method but not Javascript
ref http://www.w3schools.com/js/js_htmldom_css.asp

Related

JS multidimensional array spacefield

i wanna generate a 3x3 field. I want to do this with JS, it shall be a web application.
All fields shall inital with false. But it seems so that my code is not working correctly, but i don't find my fault. The goal is, that every spacesector is accessible.
Thats my idea:
// define size
var esize = generateSpace(3);
}
space[i] = false is replacing the array with a single boolean value false, not filling in all the entries in array you just created. You need another loop to initialize all the elements of the array.
function generateSpace(x) {
var space = [];
for (var i = 0; i < x; i++) {
space[i] = [];
for (var j = 0; j < x; j++) {
space[i][j] = false;
}
}
return space;
}
Also, your for() loop condition was wrong, as you weren't initializing the last element of space. It should have been i < space.length.
And when it's done, it needs to return the array that it created.
Since I got somewhat bored and felt like messing around, you can also initialize your dataset as shown below:
function generateSpace(x) {
return Array.apply(null, Array(x)).map(function() {
return Array.apply(null, Array(x)).map(function() {
return false;
});
});
}
The other functions work equally well, but here's a fairly simply looking one using ES6 that works for any square grid:
function generateSpace(x) {
return Array(x).fill(Array(x).fill(false));
}

passing an array into a function from within a function

I am trying to pass this arr into a function, one element at a time. I have more work to do beyond that, but I cannot even get it to send the element to the square function, so this is just a hurdle that I don't understand? Anyway, this is the code:
var arr = [1,2,3,4];
function square(element){
return element * element;
}
function applyFunction(arr, square){
for(var i = 0; i <= arr.length-1; ++i){
alert(square(arr[i]));
}
}
applyFunction(arr,square());
Any help would be appreciated, as I am sure this is simple for you guys.
Modify your last line from
applyFunction(arr,square());
to
applyFunction(arr,square);

JQuery for loop

I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));​
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}​
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?

Can I select 2nd element of a 2 dimensional array by value of the first element in Javascript?

I have a JSON response like this:
var errorLog = "[[\"comp\",\"Please add company name!\"],
[\"zip\",\"Please add zip code!\"],
...
Which I'm deserializing like this:
var log = jQuery.parseJSON(errorLog);
Now I can access elements like this:
log[1][1] > "Please add company name"
Question:
If I have the first value comp, is there a way to directly get the 2nd value by doing:
log[comp][1]
without looping through the whole array.
Thanks for help!
No. Unless the 'value' of the first array (maybe I should say, the first dimension, or the first row), is also it's key. That is, unless it is something like this:
log = {
'comp': 'Please add a company name'
.
.
.
}
Now, log['comp'] or log.comp is legal.
There are two was to do this, but neither avoids a loop. The first is to loop through the array each time you access the items:
var val = '';
for (var i = 0; i < errorLog.length; i++) {
if (errorLog[i][0] === "comp") {
val = errorLog[i][1];
break;
}
}
The other would be to work your array into an object and access it with object notation.
var errors = {};
for (var i = 0; i < errorLog.length; i++) {
errors[errorLog[i][0]] = errorLog[i][1];
}
You could then access the relevant value with errors.comp.
If you're only looking once, the first option is probably better. If you may look more than once, it's probably best to use the second system since (a) you only need to do the loop once, which is more efficient, (b) you don't repeat yourself with the looping code, (c) it's immediately obvious what you're trying to do.
No matter what you are going to loop through the array somehow even it is obscured for you a bit by tools like jQuery.
You could create an object from the array as has been suggested like this:
var objLookup = function(arr, search) {
var o = {}, i, l, first, second;
for (i=0, l=arr.length; i<l; i++) {
first = arr[i][0]; // These variables are for convenience and readability.
second = arr[i][1]; // The function could be rewritten without them.
o[first] = second;
}
return o[search];
}
But the faster solution would be to just loop through the array and return the value as soon as it is found:
var indexLookup = function(arr, search){
var index = -1, i, l;
for (i = 0, l = arr.length; i<l; i++) {
if (arr[i][0] === search) return arr[i][1];
}
return undefined;
}
You could then just use these functions like this in your code so that you don't have to have the looping in the middle of all your code:
var log = [
["comp","Please add company name!"],
["zip","Please add zip code!"]
];
objLookup(log, "zip"); // Please add zip code!
indexLookup(log, "comp"); // Please add company name!
Here is a jsfiddle that shows these in use.
Have you looked at jQuery's grep or inArray method?
See this discussion
Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?

Javascript sort not working with IE9?

the problem is I have a list with contacts and when someone change his/her status I try to move them to the top of the list. Everything worked till now, with IE9, and Firefox 4 is not working. I show you the code:
function sortByStatus()
{
var divs = getElementsByClassName(document,"status_sort");
divs.sort(compare);
for (var i = 0; i < divs.length; i++)
{
$("#contact_info").append(divs[i]);
}
}
function compare(div1, div2)
{
var id1 = div1.getAttribute("id");
var id2 = div2.getAttribute("id");
if (id1 > id2)
return 1;
else if (id1 < id2)
return -1;
else
return 0;
}
Any idea or possible fix? Thank you.
update
I have tried MrBuuBuu solution and it works patially, because now the sort by status works but the alphabetic sort is not working. I had to change part of MrBuuBuu solution, the compare function, because I compare the name of the contacts with a number just before the name that represent the status (ex. 2John , 2 means offline, and 1 online) so I have to compare with '<' and '>' and return 1, -1 or 0.
But what is worst, now it doesn't work with IE7 or IE8... the sort by status is not working.
Really weird, any idea?
document.getElementsByClassName returns a NodeList, not an array. So you have to convert it to an array first. I also cleaned up your compare() function.
function compare(div1, div2)
{
var id1 = div1.id;
var id2 = div2.id;
if (id1 < id2) {
return - 1;
}
if (id1 == id2) {
return 0;
}
return 1;
}
function sortByStatus()
{
var divs = document.getElementsByClassName("status_sort");
var divArray = $.map(divs, function(div) { return div; });
divArray.sort(compare);
$.each(divArray, function(i, div){
$("#contact_info").append(div);
});
}
If you're using the browser's native getElementsByClassName function, you may be ending up with a DOM node collection that is not a sortable Array.
When you say it's not working, are you getting any errors or is it just that the array doesn't get sorted? I'm assuming you're getting an error because sort in not defined.
One thing you could try is to clone the node collection to a plain JavaScript Array before sorting:
divs = [].slice.call(divs);
divs.sort(...
I don't have IE9 to test this, but with Chrome:
// undefined
document.getElementsByClassName("someclass").sort
But:
// the sort function
[].slice.call(document.getElementsByClassName("someclass")).sort
Are you sure it has been working? There's no such function as getElementsByClassName in the global scope.
Try using document.getElementsByClassName("status_sort") instead.

Categories