Using a for loop to display an array - javascript

I am new to arrays, and I have been trouble with making a for loop work with an array. What do I need to do?
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
for (i = 0; 1 < arrPeople.length; i++) {
text += (arrPeople[i] + '<br />');
}
}

There were a couple of minor errors in your function. The for loop statement is three parts: variable initialization, a condition that's checked after each loop, and an action that's performed after each loop. You had mistyped your condition as 1 < arrPeople.length which would always be true. Also you weren't returning a value from the function to be used by the calling code.
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
for (var i = 0; i < arrPeople.length; i++) {
text += (arrPeople[i] + '<br />');
}
return text;
}

pick your poison ...
you can also use array.foreach ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = '';
arrPeople.forEach(function(person) {
text += person + '<br />';
});
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
here's an possibly an even simpler solution using array.join ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = arrPeople.join("<br />");
text += "<br />";
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
or if you prefer, you can also use the functional style using array.reduce ...
function start() {
var arrPeople = ['Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher'];
var text = arrPeople.reduce(function(txt, itm) {
return txt + '<br />' + itm;
})
text += "<br />";
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Looks like you just want to display the list of names in the array vertically. You can do it without for-loop.
function start() {
var text = [ 'Adele', 'Ted', 'Jo', 'Jim', 'Emma', 'Kate', 'Christopher' ].join( '<br />' );
}
You can use join to concatenate each array item and you can specify a separator for each. This way there is no extra <br/>. see array.join

Related

Prevent on click function from firing multiple times

I am trying to just make a simple click function but when I do it, it fires the exact amount of times of how many items are in the array. So if I click the button I display it fires off 3 times because there's 3 items in the array (lakers, cavs, suns). My question is how do I prevent it from firing off that x number times?
var TeamPlayers = [{
team: 'Lakers',
Players: ['Russell', 'Clarkson', 'Ingram', 'Randle', 'Zubacs']
}, {
team: 'Cavs',
Players: ['Irving', 'Smith', 'LeBron', 'Love', 'Thompson']
}, {
team: 'Suns',
Players: ['Ulis', 'Booker', 'Warren', 'Chriss', 'Len']
}]
for (var i = 0; i < TeamPlayers.length; i++) {
var TeamPlayersVar = TeamPlayers[i].team
// console.log('outside loop',TeamPlayers[i].team);
$('.leftPlayer').append('<button class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
$(document).on('click', '.leftButtons', function(){
console.log(this)
});
}
I will suggest to use a id to do it . That should fix your issue. as the click will be registered with the id
for (var i = 0; i < TeamPlayers.length; i++) {
var TeamPlayersVar = TeamPlayers[i].team
// console.log('outside loop',TeamPlayers[i].team);
$('.leftPlayer').append('<button id="btn'+i+'" class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
$("#btn"+i).click(function(){
console.log(this)
});
}
This is happening because you are assigning on click listener to a class and there are 3 elements with the specified class name, in order to make it work only one time, please use ID or use unique class names
You only need to place your click handler code outside the loop i.e.
var TeamPlayers = [{
team: 'Lakers',
Players: ['Russell', 'Clarkson', 'Ingram', 'Randle', 'Zubacs']
}, {
team: 'Cavs',
Players: ['Irving', 'Smith', 'LeBron', 'Love', 'Thompson']
}, {
team: 'Suns',
Players: ['Ulis', 'Booker', 'Warren', 'Chriss', 'Len']
}]
for (var i = 0; i < TeamPlayers.length; i++) {
var TeamPlayersVar = TeamPlayers[i].team
// console.log('outside loop',TeamPlayers[i].team);
$('.leftPlayer').append('<button class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
}//for()
$(document).on('click', '.leftButtons', function(){
console.log(this)
});

Get element from array by value in Javascript

I have simple code which allows me display related product based on tags, but I would like expand that code, that can I type more than one tag. At this moment I can run only:
<script type="text/javascript">category('tag1');</script>
And I got every product with 'tag1' in their tags. In this case name1 and name2.
var products = [
{
name: 'name1',
tags: ['tag1', 'tag2', 'tag3'],
},
{
name: 'name2',
tags: ['tag1', 'tag3', 'tag4', 'tag5'],
},
{
name: 'name3',
tags: ['tag2', 'tag5', 'tag6'],
}
];
var finalHtml = "";
function category(tag) {
return products.filter(function(product){
if (~product.tags.indexOf(tag)) {
finalHtml += '<li>' + product.name + '</li>';
document.getElementById("related_prod").innerHTML = finalHtml;
}
});
}
What I expect?
When I will run that code:
<script type="text/javascript">category('tag1, tag6');</script>
I would like see every product which has tag1 OR tag2 in their tags. In this case it should be name1 and name3.
Here is a solution using ECMAScript2015:
var products = [
{
name: 'name1',
tags: ['tag1', 'tag2', 'tag3'],
},
{
name: 'name2',
tags: ['tag1', 'tag3', 'tag4', 'tag5'],
},
{
name: 'name3',
tags: ['tag2', 'tag5', 'tag6'],
}
];
function category(...tags) {
let related = document.getElementById("related_prod");
// clear output
related.innerHTML = '';
// turn array values into object properties for faster lookup
tags = tags.reduce((tags, tag) => (tags[tag] = 1, tags), {});
// find products that have at least one of the tags
products.filter(product => product.tags.some(tag => tags[tag]))
// display the names of the found products
.forEach(product => {
let li = document.createElement('li');
li.textContent = product.name;
related.appendChild(li);
});
}
category('tag4','tag5');
<ul id="related_prod"></ul>
This can be mor generic as i understand from your requirement you wanted "OR" not "AND" so the answer can be :
function category() {
var args = Array.prototype.slice.call(arguments);
return products.filter(function(product){
args.forEach(function(arg){
if (product.tags.indexOf(arg)> -1) {// readability
finalHtml += '<li>' + product.name + '</li>';
document.getElementById("related_prod").innerHTML = finalHtml;
}
})
});
}
Edit: For a better solution that have good seperation and readable one (assuming you are using ecmascript5 shim)
function findProducts(){
var args = Array.prototype.slice.call(arguments);
var foundProducts = [];
products.forEach(function(product) {
args.forEach(function(arg){
if(product.tags.indexOf(arg) > -1 && foundProdutcs.indexOf(product) == -1)
foundProducts.push(product);
}
});
return foundProducts;
}
function doSomethingWithTheProducts() {
var products = findProducts.apply(this,arguments);
var finalHtml = "";
products.forEach(function(product){
finalHtml += "<li>" + product.name + "</li">;
});
document.getElementById("related_prod").innerHTML = finalHtml;
}
doSomethingWithTheProducts('tag1','tag2');

javascript document element by id

If I need to see my out put in the page not in console.log i want use document get Element By Id how can i do that? he gave me just one result, Steve only !!
[Code: ]
http://i.stack.imgur.com/ISqzT.png
<script>
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['Microsoft Way']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobes",
number: "(444) 111 000",
address: ["Apple way"]
};
var list = function(obj) {
for( var key in obj){
console.log(obj);
document.getElementById("demo").innerHTML = key + "<br>";
}
}
var search = function(name) {
for(var key in friends){
if(name === friends[key].firstName){
console.log(friends[key]);
}
}
}
list(friends);
// search("Steve");
</script>
Hey the only change you have to make is using += instead of just = for the innerHTML function. Here you go:
text.innerHTML+=friend + "";
Simply append the result to your innerHTML, do not overwrite it, likewise:
document.getElementById("demo").innerHTML += key + "<br>";

How to add Rowspan in JQuery datatables

Im using Jquery datatables to construct a table.
My requirement is like below
This is not a static table, and we are rendering it using json data. Here I'm, rendering the rows dynamically using "aoColumns".
Is there any way to use rowspan so that the cells (1,2,David,Alex) can be spanned.
Does datatables support this kind of table ?
Datatables does not support this kind of grouping out of the box.
But, as in many cases, there is a plugin available.
It is called RowsGroup and is located here: Datatables Forums. A live example is also included.
If you change the JS part in this example to the below you will have your desired output presented to you in the output window.
$(document).ready( function () {
var data = [
['1', 'David', 'Maths', '80'],
['1', 'David', 'Physics', '90'],
['1', 'David', 'Computers', '70'],
['2', 'Alex', 'Maths', '80'],
['2', 'Alex', 'Physics', '70'],
['2', 'Alex', 'Computers', '90'],
];
var table = $('#example').DataTable({
columns: [
{
name: 'first',
title: 'ID',
},
{
name: 'second',
title: 'Name',
},
{
title: 'Subject',
},
{
title: 'Marks',
},
],
data: data,
rowsGroup: [
'first:name',
'second:name'
],
pageLength: '20',
});
} );
Here is a screenshot of the result:
I tried the RowsGroup plugin, but it achieves this just by hijacking the DataTables sort mechanism. If you tell it to group a given column, what it does for you is basically to apply a sort to that column that you can't turn off. So, if you want to sort by another column, you can't. That didn't work in my application.
Instead, here's a working fiddle for a recipe that allows you to achieve this result:
https://jsfiddle.net/bwDialogs/fscaos2n
The basic idea is to flatten all of your multi-row data into a single row. Content in your 2nd, 3rd, etc. rows are stored as a hidden <script> template tag within your first row.
It works by using DataTables' drawCallback function to manipulate the DOM once DataTables has rendered it, without confusing DataTables by having to try parsing rowspan cell content.
Since this modifies the DOM after DataTables has done its magic, your multi-row sections will stick together even with pagination, searching, and sorting.
Cheers.
add a below code and modify according to your requirement
$(window).on("load",function() {
MakeRows();
addRowspan();
$(".paginate_button").on("click", function() {
MakeRows();
addRowspan();
});
});
function MakeRows() {
var tmp_tbl = $("#dashboardDetails");
var _l = tmp_tbl.find("tr");
var _td = "",_t_td = "", old_txt = "",_t_txt = ""; _tr_count = 1;_tr_countadd = 1;
for(i = 0;i< _l.length; i ++) {
_t_td = tmp_tbl.find("tr").eq(i).find("td").eq(0).find("span");
_t_txt = $(_t_td).text();
_t_txt = _t_txt.replace(/\//,"_");_t_txt = _t_txt.replace(/\//,"_");
if (_t_txt.length > 0) {
if(_t_txt != old_txt) {
if($(_l).eq(i).hasClass(_t_txt) == false) {
_tr_count = 1;_tr_countadd = 1;
$(_l).eq(i).addClass("" + _t_txt + "").addClass(_t_txt + "_" + i);
}
old_txt = _t_txt;
} else {
_tr_count = _tr_count + 1;
if (_tr_countadd == 1) {
$(_l).eq(i).addClass("" + _t_txt + "").addClass(_t_txt + "_" + i)
.addClass("hiddenClass").addClass("maintr").attr("trcount", _tr_count).attr("addedtrcount", "maintr");
_tr_countadd = _tr_countadd + 1;
} else {
$(_l).eq(i).addClass("" + _t_txt + "").addClass(_t_txt + "_" + i)
.addClass("hiddenClass").attr("trcount", _tr_count)
}
}
}
_t_td = "";
}
}
function addRowspan() {
var t_txt = "";
var _alltrmain = $(".maintr");
var _h_td = ["0","10","11","12","13"];
for (i = 0; i <= _alltrmain.length; i ++) {
for (j = 0; j <= _h_td.length; j ++) {
t_txt = $(_alltrmain).eq(i).attr("trcount");
$(_alltrmain).eq(i).prev().find("td").eq(_h_td[j]).attr("rowspan", t_txt);
}
}
}

Add to element as divs

Okay, so here's my code:
HTML:
<h2>Header</h2>
<div id="results1" class="results">
<h1>Results 1</h1>
</div>
JS:
(function() {
var results = document.getElementById('results1');
var drink = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
})();
I need to add the drinks to the results element as divs.
Just a simple for loop to iterate over the array, and then append each item to the results div.
for (var i = 0 ; i < fruit.length; i++) {
results.innerHTML += "<div>" + fruit[i] + "</div>";
};
JSFiddle Demo
With pure JavaScript:
(function() {
var results = document.getElementById('results1');
var fruits = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i = 0; i < fruits.length; i++){
var fruit = document.createElement('div').innerHTML = fruits[i];
results.appendChild(fruit);
}
})();
Demo
try like this
var parent = $("#results1");
var fruit = ['Rum', 'Vodka', 'Whiskey', 'Beer'];
$.each(fruit, function (i, val) {
parent.append("<div id=" + val + " >" + val + "</div>");
});
You can use this:
js
(function() {
var results = document.getElementById('results1');
var fruit = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i=0; i<fruit.length; i++){
var div = $("<div>" + fruit[i] + "</div>");
$(div).appendTo("#results1");
}
})();
fiddle
(function() {
var results = document.getElementById('results1');
var fruit = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i=0; i<fruit.length;i++){
$("#results1").append('<div>'+fruit[i]+'</div>');
}
})();
fruit.forEach(function(value,index){
var div = document.createElement('div');
div.innerHTML = value;
$("#results1").append(div);
});
You may try this one:
(function() {
var results = document.getElementById('results1');
var drink = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
results.innerHTML += '<div>' + drink.join('</div><div>') + '</div>';
})();
This is the for loop you could use for javascript
and incorporated it into your html.
var drink = ["Rum", "Vodka", "Whiskey", "Beer"];
for (index = 0; index < drink.length; ++index) {
text += drink[index];
}

Categories