Iterating an array that is nested with an object key - javascript

var html = {
easyBB :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb:
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB2:
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb2 :
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB3 :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb3 :
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png']
};
var cont = document.getElementById('container');
for(var key in html){
for(var i =0;i<key.length;i++ ){
var name= '<span class="name">'+html[key][0] +'</span>',
link = '<span class="url">'+html[key][1] +'</span>',
image = '<img src="'+html[key][2]+'" title="'+html[key][0]+'" />';
cont.innerHTML= '<div class="wrapper">'+ name + '<br />'+image+'<br />'+link+'</div>';
i++;
}
}
I am trying to iterate over the arrays in each key of the HTML object I created problem is not sure how to do this I've tried multiple ways now and I believe (since I am posting) I am doing this all wrong. I've also tried doing: html[key[i]][0] though of course I get an error of i is not defined. Any suggestions what I am doing wrong, as of right now it is only posting one array to the html.

The problem is not the iteration, it's the line
cont.innerHTML = ...
which is replacing the content each time the loop iterates so that you only see the final item ("AvacWeb3").
Change that to
cont.innerHTML += ...
and get rid of the for (var i =0 ... loop which isn't needed. (jsfiddle)

for(var i = 0; i < html[key].length; i++){
...

You should do html[key][i][0].
And also you should do what Trevor said, html[key].length instead of key.length.
Make yourself easy by assigning html[key] to var currentkey for example, easier to keep track on.
Also, look into array.forEach, just for fun ;)

Related

How to merge duplicate values in a for loop javascript

I am new to js and I don't understand much of codes and conditions in js.
My question is simple but I need someone to give me a good example if possible as I know what I need but it is getting hard to implement that in code.
This is my code with 2 arrays where the data is coming from.
blind_tmp = '';
for (i=0; i<#All of Blind Relationship Link.length; i++){
blind_tmp = blind_tmp + '<p>[**' + #All of Element Title[i] + '**](' + #All of Blind Relationship Link[i] + ')'
};
What simple needed is that. I want merge records that are duplicates printed.
for example: if Blind Relationship link is AF44 and after 6 elements this AF44 comes again so I want both to be written like 1.AF44,2.AF44
while now it is writing the elements how they come along
example:
AF11,AF22,AF33,AF44,AF55,AF66,AF77,AF44
so in this example you see two AF44
I want them to be written like this
AF11,AF22,AF33,AF44AF44,AF55,AF66,AF77
any help with a code example is appreciated.
The idea is to iterate through each element in the blindRelationshipLink and store those elements in a temporary array which will be used to check the number of occurrence of an array element.
var blindRelationshipLink = ['AF11','AF22','AF33','AF11','AF44','AF44','AF55','AF66','AF77','AF11','AF22','AF11'];
var arrTemp = [];
var p = '';
blindRelationshipLink.forEach(function(arr){
var count = 0;
arrTemp.forEach(function(a){
if(arr === a)
count++;
});
arrTemp.push(arr);
if(count){
count++;
arr= arr + '.' + count;
}
p = p + arr + ',';
});
alert(p);
You test by running the code snippet.
This approach is not best but it may serve your purpose.
Here is a snippet
var elemArray = ['AF11', 'AF22', 'AF33', 'AF44', 'AF55', 'AF66', 'AF77', 'AF44']; // Array of elements
//A new array which which will contain elements which pass our case
var finalArray = [];
elemArray.forEach(function(item) { // loop through main array
// Check if element is present or else push the element
if (finalArray.indexOf(item) == -1) {
finalArray.push(item);
} else {
// if element is there find the index
var getIndex = finalArray.indexOf(item);
// remove the element, else there will be duplicate
finalArray.splice(getIndex, 1);
//concate the matched element
var newElem = item + item;
// push the element in specfic index
finalArray[getIndex] = newElem;
}
})
console.log(finalArray)
Current drawback with this code is what will happen if there are multiple repeated item in the main array. For example presence of AF33 more than twice.
DEMO

For loop only outputs last iteration

I am new to Javascript and am just playing around trying to print a simple for loop to the HTML.
HTML:
<div id="hello"</div>
JS :
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").innerHTML=text+i;
}
My problem is that this code only outputs the last iteration '9', and not '0123456789' which is what I want.
Now if i do document.write it prints out the numbers fine but I heard this is bad practice so I just want to do it the correct way.
Thanks
It would be better to build your text content first and insert it into HTML element once (to save some time):
var text="";
for (var i=0;i<10;i++) {
text += i;
}
document.getElementById("hello").innerHTML = text;
You should use the addition assignment operator += that adds a value to a variable, so you're just missing + before = in :
document.getElementById("hello").innerHTML += text+i;
NOTE : Use textContent instead of innerHTML because you're appending just a text, check example bellow.
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").textContent += text+i;
}
<div id="hello"></div>

When an I print out an array How do I make it listed?

When I go to print out an array, That may have items put into it at later times, like this:
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx);
//or
document.write(ArrayEx);
It usually just prints it all out in one big blob of text. I was wondering, if I make it print in the alert box or the document, how i can make it a list, going down, or just with a , in between each one. Does anyone know how I could do that?
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
var joined = ArrayEx.join(", ");
console.log(joined);
This will log
"Zero, One, Two"
Here's a quick and simple way to loop through an array and list the items in the array:
http://jsfiddle.net/mjgbm6c3/
HTML
<ul class="sample-list"></ul>
JS
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
for(var i = 0; i < ArrayEx.length; i++){
var item = '<li>' + ArrayEx[i] + '</li>';
$('.sample-list').append(item);
}
Have a look at the Array.join() method, it will build a string out of the elements in the array and separate them with the string you pass to the separator parameter.
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx.join(', '));
// and
document.write(ArrayEx.join(', '));
// would both output: Zero, One, Two
For a new line, replace ', ' with '\n' in alerts and '<br />' in anything going to HTML; such as document.write().
document.write(ArrayEx.join('</br>'));

showing selected names in a <div> by using a javascript array

I have a div which displays name of the people who are online, I have the following members in
the div
<div id="members">
<span>Amlan Karmakar</span>
<span>Atin Roy</span>
<span>Arpan Burman</span>
<span>Ramanuj Mukherjee</span>
</div>
I have another javascript array friends[], which has 'Amlan Karmakar' and 'Ramanuj Mukherjee' has friends, I want to display those members who are in the friends[] array, I am inserting the name of the friends by friends.push("Amlan Karmakar"). The names in div are auto generated by cometd chat, I have written the names in the div for simplicity. I hope there is a solution to this problem. My previous question didn't solve my problem.
You could try something like the below, i.e. split the HTML of the div containing the members, loop through them and check if they are in the friendsArray. Note that this is a rough implementation, and that it assumes a reasonably new browser as it uses Ecmascript 5 features. The concept can applied using old-fashioned for loops too.
var all = document.getElementById('members').getElementsByTagName('span');
var friendsOnly = '';
for(var i=0; i<all.length; i++){
if(friendsArray.some(function(friend){
return friend == all[i].innerHTML;
})){
friendsOnly += '<span>' + all[i].innerHTML + '</span>';
}
});
all.innerHTML(friendsOnly);
By the way, I'm assuming the friendsArray may contain people who are not already in the div. If that is not the case, then I'm not sure what the question is about.
So you want to put the data from the friends[] array into the <div id="members">
I want only those names to show in the which are there in the friends[] array
If you only want to display the names which are in the friends array, as you suggested in your comment, I suppose this will do the trick:
var target = document.getElementById("members");
// Remove this line if you want to keep the current names in the members div.
target.innerHTML = ""; // Clean before inserting friends
for (var i = 0; i <= friends.length; i++) {
target.innerHTML += friends[i] + "<br />"; // Add friend + break
}
Try this to get only the friends out of the list of members:
var friendMembers = document.getElementById('members').split(/<br\s*[\/]?>/gi)
.filter(function(member) { return (friends.indexOf(member) > -1) } );
You should try knockout.js, this framework will help you handle this case.

Adding a javaScript array to a HTML page?

Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:
text1
text2
text3
...
The code I have used so far is:
var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList="";
for (i=0;i<test.length; i++) {
testList+= test[i] + '<br />';
}
$('#here').html('testList');
songList="";
});
I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks
Try without quotes:
$('#here').html(testList);
-or-
$('#here').html(test.join('<br />'));
Another approach:
var html = ''; // string
$.each(test,function(i,val){ // loop through array
var newDiv = $('<div/>').html(val); // build a div around each value
html += $('<div>').append(newDiv.clone()).remove().html();
// get the html by
// 1. cloning the object
// 2. wrapping it
// 3. getting that html
// 4. then deleting the wrap
// courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});
$('#here').html(html);
There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.
Try changing the line
$('#here').html('testList')
to
$('#here').html(testList)
What you have works if you remove the single quotes from testList. However, if you would like an actual unordered list you can do this. (here's a jsFiddle)
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList=$("<ul></ul>");
for (var i=0;i<test.length; i++) {
$(testList).append($("<li></li>").text(test[i]));
}
$('#here').html(testList);
songList="";
}); ​
This line:
$('#here').html('testList');
shouldn't have single quotes around testList - you want to use the content of the variable, not the string literal "testList".
Don't pass the variable as a string : $('#here').html('testList'); Pass it without quotes : $('#here').html(testList);
Here's the simplest version:
$(document).ready(function() {
var test = ["text1", "text2", "text3"];
$('#here').html(test.join("<br>"));
});

Categories