Using an array as the text content - javascript

I am trying to create a system to place a the values of the array into the text.
Array:
var records = [
['C', 'Descript']
['D', 'Test']
];
Creates the 'th' that I want to put the array values in.
let newColItem = document.createElement('th');
What I have tried:
galleryheader.textContent = records[i,1];
The i is from a for loop. No values a showing in the galleryheader cell. I can't find anything on how to put the array inside on the web, anyone got some idea of what to do.
All code if you need it:
const gallery_table = document.getElementById("gallery_table");
let list = ["A", "B"];
var idName = "";
var records = [
['C', 'Descript']
['D', 'Test']
];
for (let i = 0; i < list.length; i++) {
if (i % 3 === 0) {
var newRowItem = document.createElement("tr");
idName = "newRowItem";
idName = idName.concat(i);
newRowItem.setAttribute("id", idName);
gallery_table.appendChild(newRowItem);
}
let newColItem = document.createElement('th');
let galleryheader = document.createElement('h3');
newColItem.setAttribute("class", i);
newRowItem.appendChild(newColItem);
newColItem.appendChild(galleryheader);
galleryheader.textContent = records[i,1];
const element = document.getElementById(idName);
let nodes = element.getElementsByClassName(i);
for (let j = 0; j < nodes.length; j++) {
nodes[j].style.padding = "2px";
nodes[j].style.width = "33%";
nodes[j].style.border = "1px solid black";
}
}

Related

How to create many elements and add them to another many elements?

Hi i have problems with creating many elements and adding to them many elements and then append them to another elements.
my code looks like this:
const createElementsFromLocalStorage = (event) => {
for (let i = 0; i < allRecipes.length; i++) {
let optionValue = document.createElement('option');
optionValue.value = allRecipes[i].title;
for(let j = 0; j < allDaysDataLists; j++) {
allDaysDatalists[j].appendChild(optionValue);
}
}
}
So i want to create optionValue "i" times and set them values with each allRecipes.title. It should looks like this for example:
I have array allRecipes = [1, 2, 3, 4, 5]
So I want to create 5 times optionValue and each optionValue should have .value depends on array index. For example: optionValue.value = 1, optionValue.value = 2, optionValue.value = 3, optionValue.value = 4, optionValue.value = 5. Then I want to append all this optionValue elements to each allDaysDataLists. So each allDaysDataLists should have all this created optionValue.
for(let i = 0; i < allDaysDataLists.length; i++) {
for(let j = 0; j < allRecipes.length; j++) {
const optionValue = document.createElement('option');
optionValue.value = allRecipes[j].title;
allDaysDatalists[i].appendChild(optionValue);
}
}
can you try this?
const createElementsFromLocalStorage = (event) => {
allRecipes.forEach(r => {
allDaysDatalists.forEach(select => {
select.options[select.options.length] = new Option(r.title, r.title);
});
});
}

mapping a 3x3 grid in javascript

In practicing understanding arrays and how to loop through them, I wrote a function to map each row, column and two diagonals into their own key value pair.
Is there a more efficient way of looping through this? I know it's bad practice to use two for loops as it leads to high complexity if the grid were bigger than 3x3.
let board = [
[1,2,3],
[4,5,6],
[7,8,9]
];
const mapper = board => {
let
map = {},
d1 = [],
d2 = [];
for (let i = 0; i < board.length; i++) {
let tmp = [];
// get all rows
map[`R${i}`] = board[i];
// get second diagonals
d2.push(board[i][board.length-1-i]);
for (let j = 0; j < board.length; j++) {
// get all columns
tmp.push(board[j][i]);
// get first diagonals
if (i === j) {
d1.push(board[i][j])
}
}
map[`C${i}`] = tmp;
}
map[`D1`] = d1;
map[`D2`] = d2;
return map;
}
console.log(mapper(board));
The below is arguably clearer, and could be imporved futher by using reduce.
board = [
[1,2,3],
[4,5,6],
[7,8,9]
];
diag = 0; map = {}
board.forEach((row,r,arr) => {
var rows = arr.length-1;
map['R'+r] = row;
map['D'+1] = map['D'+1] || [];
map['D'+2] = map['D'+2] || [];
map['D'+1][diag] = row[diag];
map['D'+2][rows-diag] = row[rows-diag]
diag++;
row.forEach((col,c) => {
map['C'+c] = map['C'+c] || [];
map['C'+c].push(col);
});
});
console.log(map);

Issues with array[i].match and array[i].substring

I wanna use array[i].match and array[i].substring but this presents a problem to me.
If I wanna output this matches I get a blank page.
JavaScript
var List = ["example1", "example2", "example3", "example21", "example12"];
var array = [];
for (var i = 0; i < List.length; i++) {
Entry = List[i];
var counts = Entry.match(/1/g).length;
//var n = Entry.search("example1");
if (counts >= 1) {
array.push(Entry);
}
}
for (var i = 0; i < array.length; i++) {
var Eintrag = document.createElement("div");
Eintrag.style.background = "DodgerBlue";
Eintrag.style.width = "50px";
Eintrag.style.height = "10px";
Eintrag.style.marginLeft = "1%";
Eintrag.style.marginRight = "1%";
Eintrag.style.border = "thin solid red";
CallOutputBox.appendChild(Eintrag);
}
With array[i].search it works fine.
It's not working because you're assuming there will be an array. If there's no match, there's no array. So you need to check to see if counts exists and then check the length.
DOCS
An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.
DEMO
var counts = Entry.match(/1/g);
if (counts && counts.length >= 1) {
// do stuff
}

Javascript : how to slice an array of objects?

So, I have an array of objects like this:
for(var i=0; i<travelcard_table.length;i++){
var table_row = travelcard_table.eq(i);
var ii = 0;
passenger_info[i] = {};
table_row.find("td").each(function() {
passenger_info[i][table_keys[ii]] = $(this).text();
ii++;
});
}
passenger_info[0]['First name'] = "John"; etc..
passenger_info[1]['First name'] = "Chuck"; etc..
Im trying to split this to smaller arrays of objects every 10 entries, so Its something like this:
var size = 10;
for (var i=0; i<passenger_count; i+=size) {
var smallarray = passenger_info.slice(i,i+size); << "Error: Slice is not a function"
console.log(smallarray);
// do something with smallarray
}
How to achieve this?
var passenger_info = [[], []];
passenger_info[0]['First name'] = "John";
passenger_info[1]['First name'] = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0]['First name']);
This alerts 'John', because passenger_info is an Array of Array objects and you are attaching properties to the array object and not to its items.
for an array of objects it should be:
var passenger_info = [ {} , {}];
passenger_info[0].firstname = "John";
passenger_info[1].firstname = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0].firstname);
like this you can workout
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [];
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
smallArray.push(passenger_info[i+j]);
}
console.log(smallArray);
}
for using slice you can do like this
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [],ls;
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
ls = i+j;
}
smallArray = passenger_info.slice(i,ls+1);
console.log(smallArray);
}

JavaScript: assigning to array in nested loops

I'm working on a codecademy.com lesson on arrays. I'm supposed to write nested loops to put each card of every suit in a deck of cards in an array.
I'm really messing this up. This is one combination that I've tried that doesn't work. The only indication that I have that I'm sort of close is that it returns "52" so at least 52 objects are going into the array. can anyone point out what I'm doing wrong?
//array 1: the suits
var suits = ["clubs","hearts","diamonds","spades"];
//array 2: the ranks
var ranks = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
//using for loops, modify the "deck" array so that it becomes a
//two-dimensional array that stores every card in the deck;
//e.g. [1, "clubs"], [2, "clubs"],etc...["A", "spades"]
var deck = [];
for(i = 0; i < suits.length; i++){
for (j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
deck.push(cardArray);
}
}
Each iteration, a new array is being added to deck that looks like the following:
cardArray: [ [ ranks[j] ] ]
When cardArray[0][0] is set, it is overwriting cardArray[0] as an array with index 0 containing ranks[j]. Instead, set cardArray[0] to suits, and cardArray[1] to ranks.
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
This results in:
for (var i = 0; i < suits.length; i++){
for (var j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
}
}
You should use a var declaration for your loop counter. Your problematic code is
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
which does things like
var foo = "clubs";
foo[0] = "J";
which obviously does not work. I think what you want is
var deck = [];
for(var i = 0; i < suits.length; i++){
var cardArray = [];
for (j = 0; j < ranks.length; j++){
var twoCards = [];
twoCards[0] = suits[i];
twoCards[1] = ranks[j];
cardArray.push(twoCards);
// // or the same thing as this loop body, shorter:
// cardArray.push([suits[i], ranks[j]]);
}
deck.push(cardArray);
}

Categories

Resources