How do I access the contents of multi-dimensional arrays? - javascript

I'd like to create a multi-dimensional array so that I can eventually iterate through each array's contents.
The end goal is to be able to do something like this:
websiteURL[x]image[y].imageALT[z]
I think I can do this by creating a multi-dimensional array and adding properties where needed. If this is wrong, please let me know any possible alternatives and ignore the following question.
If it sounds about right, here's what I've got for multi-dimensional arrays:
container = [['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png'], ['This is alt text 1.', 'This is alt text 2'], ['https://amazon.ca', 'https://google.ca']];
var imageSRC = container[0]
var imageALT = container[1]
var imageCTA = container[2]
imageSRC[0];
container[0];
No output is given when I run this.

You're right so far. The trick to it is to use the numbers in the square brackets next to each other.
container = [
// 0
['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png'],
// 1
['This is alt text 1.', 'This is alt text 2'],
// 2
['https://amazon.ca', 'https://google.ca']
];
So container[0] refers to the following:
['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png']
And container[0][0] refers to:
'https://amazon.ca/logo.png'
For complex things, I usually use Objects which are a bit friendly to work with.
container = [{
image: 'https://amazon.ca/logo.png',
alt: 'This is alt text 1.',
url: 'https://amazon.ca',
},
{
image: 'https://google.ca/logo/logo.png',
alt: 'This is alt text 2',
url: 'https://google.ca',
}]
console.log(container[1].alt) // 'This is alt text 2'

Related

How to fix Javascript associative array error

I am trying to display a list of images with their titles stored in an associative array. But the code only displays the last image and title in the array, in the browser not all of them. However when I console log the values: value.title and value .image the full list is displayed in the console. I must be missing something simple any pointers would be welcome.
<center id="pics"></center>
<script>
const photos = [
{
title: "Landscape River",
image: "landscape1.png",
},
{
title: "Landscape Mountains",
image: "landscape2.png",
},
{
title: "Landscape Mountain Road",
image: "landscape3.png",
},
{
title: "Landscape Hills and Lake",
image: "landscape4.png",
},
];
photos.forEach((value) => {
console.log(value.title, value.image);
document.getElementById("pics").innerHTML =
`<img src="images/${value.image}" >` + "<br>" + value.title;
});
</script>
</body>
While the accepted answer kind of works, it is a not a good solution, because it leads to totally unnecessary re-rendering of the DOM with every loop iteration. And that is just the performance side of the story; using innerHTML also is bad security-wise.
Instead, create those elements dynamically using document.createElement, append it to a documentFragment, and when the loop is done, append that fragment to the actual DOM.
That being said, this is what a proper solution could look like:
const picsContainer = document.getElementById("pics");
const fragment = new DocumentFragment();
photos.forEach(({image, title}) => {
const img = document.createElement('img');
img.src = `images/${image}`;
const br = document.createElement('br');
const text = document.createTextNode(title);
fragment.append(img, br, text);
});
picsContainer.append(fragment);
You will want to do document.getElementById("pics").innerHTML += instead of just =. You want to append each title and image, and not reset the innerHTML every time with a new title/image if that makes sense. Happy coding!

HTML code generation from string using Javascript

I am developing a javascript tool that will extract the string, obtain relevant strings and create html tags.
const string = "Create heading 1 that will have class abc and id xyz";
const elementList = [
{name: 'heading 1', tag: 'h1'},
{name: 'heading 2', tag: 'h2'}
{name: 'paragraph', tag: 'p'},
];
function convertTag(input) {
return elementList.reduce((acc, a) => {
const re = new RegExp(a.name,"g");
return acc.replace(re, a.tag);
}, input);
}
let initialString = convertTag(string)
//returns create h1 that will have class abc and id xyz
let htmlElement = initialString. split (" ")[1]; // will return h1
let code = `<${htmlElement}> </${htmlElement}>`;
How do I include class and Id? There
might be other attributes like alt, src etc. Is there any library to grab the HTML attributes?
Thank you
The result of running the following code is abc xy being printed in the console.
The idea is to search for the prefix "class " and "id " then grab 1 or more alphanumeric characters, bunch em together and return them. The match function returns a bunch of things, including the position within the string. Since we're just interested in the 1st (only!) result, we can grab element 0 from the result, treating it like a simple array.
The half-awake will note that these simple regexes would allow number to start the following group. Rather than grabbing 1 or more alphanumerics, I suppose a more robust solution would be to grab 1 alpha AND 0 or more alphanumerics.
Someone put me onto Expresso as a useful (free) tool to play around with regexes on the desktop.
function test1()
{
const s = 'Create heading 1 that will have class abc and id xy';
let cl = s.match(/(?<=class )\w+/)[0];
let id = s.match(/(?<=id )\w+/)[0];
console.log(cl,id);
}

Accessing an element in an array within an array in JavaScript

Pastebin of index.html: http://pastebin.com/g8WpX6Wn (this works but with some broken img links & no css).
Zip file if you want to see whole project:
I'm trying to dynamically change the contents of a div when I click an image. The image has it's respective id (the first index in the inner array) within the first inner array there's another array (index 3). I want to populate my div (id="articleLinks") with those links using JQuery when the image is clicked.
JavaScript & JQuery:
The tube array. *Note: the first index of each element in tubeArray is the ID & the news articles aren't linked to anything particular. Only interested in tubeArray[0] & tubeArray[4]
var tubeArray = [
['UQ', -27.495134, 153.013502, "http://www.youtube.com/embed/uZ2SWWDt8Wg",
[
["example.com", "Brisbane students protest university fee hikes"],
["example.com", "Angry protests over UQ student union election"],
]
],
['New York', 40.715520, -74.002036, "http://www.youtube.com/embed/JG0wmXyi-Mw",
[
["example.com" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]
]
],
['To The Skies', 47.09399, 15.40548, "http://www.youtube.com/embed/tfEjTgUmeWw",
[
["example.com","Battle for Kobane intensifies as Islamic State uses car bombs, Syrian fighters execute captives"],
["example.com","Jihadists take heavy losses in battle for Syria's Kobane"]
]
],
['Fallujah', 33.101509, 44.047308, "http://www.youtube.com/embed/V2EOMzZsTrE",
[
["example.com","Video captures family cat saving California boy from dog attack"],
["example.com","Fines of £20,000 for dogs that chase the postman"]
]
]
];
A for loop which goes through each element in tubeArray then assigns id to the first index. Also an image that calls the function myFunctionId which takes the parameter this.id.
for (i = 0; i < tubeArray.length; i++) {
var id = tubeArray[i][0];
//other code
'<img src="img.png" onclick="myFunctionId(this.id);" id="' + id + '">' +
//other code
}
function myFunctionId (id) {
journal = id;
alert(journal) //just a test
//I want to search through tubeArray with the id and find the matching inner array.
//I then want to loop through the innerArray and append to my html a link using JQuery.
for (j = 0; i < innerArray.length; j++){
//supposed to get "www.linkX.com"
var $link = ;
//supposed to get "titleX"
var $title = ;
//change the content of <div id="articleLinks">
$('#articleLinks').append('<a href=$link>$title</a><br>');
}
}
HTML:
<div id="articleLinks">
Example Link<br>
</div>
Any help would be greatly appreciated. I've tried to simplify & cut out as much as I can so it's readable.
probably this might help: make yourself a map like
var tubeArray = [
[ // tubeArray[0]
'id', // tubeArray[0][0]
int, // tubeArray[0][1]
int, // tubeArray[0][2]
[ // tubeArray[0][3]
[ // tubeArray[0][3][0]
"www.link1.com", // tubeArray[0][3][0][0]
"title1" // tubeArray[0][3][0][1]
],
[ // tubeArray[0][3][1]
"www.link2.com", // tubeArray[0][3][1][0]
"title2" // tubeArray[0][3][1][1]
]
]
],
etc.
don't know whether this helps, but four dimensional arrays are brain-breaking ....
[edit]
... and thus go for a more OO like approach:
var tubeArray = [
'id' : { // tubeArray[id] or tubeArray.id
'a': int, // tubeArray.id.a
'b': int, // tubeArray.id.b
'entries': [ // tubeArray.id.entries
{ // tubeArray.id.entries[0]
'url': "www.link1.com", // tubeArray.id.entries[0].url
'title': "title1"
},
{ // tubeArray.id.entries[1]
'url': "www.link2.com", // tubeArray.id.entries[1].url
'title': "title2" ...
}
]
] ,
First you need to loop over tubeArray then go 4 deep and loop over the Array of Arrays at that level. Of course, you loop over those inner Arrays and get Elements 0 and 1.
$.each(tubeArray, function(z, o){
$.each(o[4], function(i, a){
$.each(a, function(n, v){
$('#articleLinks').append("<a href='"+v[0]+"'>"+v[1]+'</a>'); // use CSS to break lines
});
});
}

Randomize text, embed codes and URL's from list

I have a list with movie titles, youtube URL's (with which I can construct an embed code) and URL's to IMDB. On every page refresh, another movie title, Youtube video, and text with a URL to IMDB has to appear.
["Movie A", "URL_to_youtube_movie_A", "URL_to_IMDB_movie_A"],
["Movie B", "URL_to_youtube_movie_B", "URL_to_IMDB_movie_B"],
etc.
My website already has a refresh button: the page reloads with . How can I make the youtube video displayed randomized? I want the output to be HTML, so I can add elements afterwards, if necessary.
Shuffle the array, you can use underscore, or write custom function:
list = _.shuffle(list)
then output first n movies. This is the simplest method, that I think will be good enough for your case.
I would make an array of objects. Movie is an object, like this:
var list = [{ title: "Movie A", urlYouTube: "URL_to_youtube_movie", urlImdb: "URL_to_IMDB_movie_A"}, ...]
Also if you plan to do more operations than just show the random movies look at some javascript frameworks(backbone.js, angular, ...).
I would recommend you to use templates for the HTML output. Underscore also has simple template implementation. _.template(templateString, [data], [settings])
Something like this: DEMO && CODE
With simple javascript without any Library
You will need suffle function like below
DEMO
function arrayShuffle(oldArray) {
var newArray = oldArray.slice();
var len = newArray.length;
var i = len;
while (i--) {
var p = parseInt(Math.random()*len);
var t = newArray[i];
newArray[i] = newArray[p];
newArray[p] = t;
}
return newArray;
};
Call it like
var list = [{ title: "Movie A", urlYouTube: "URL_to_youtube_movie_A", urlImdb: "URL_to_IMDB_movie_A"},
{ title: "Movie B", urlYouTube: "URL_to_youtube_movie_B", urlImdb: "URL_to_IMDB_movie_B"},
{ title: "Movie C", urlYouTube: "URL_to_youtube_movie_C", urlImdb: "URL_to_IMDB_movie_C"}];
var Suffledlist = arrayShuffle(list);
And then show top 2 or 5 elements

Adding new element to associative array each click

This is probably very easy, but I just can't figure out how to solve it right now. Each time a submit button is clicked, the function below checks input field 1 (name), and if not empty adds the value to an associative array, and continue with the description.
What I want is to add a new level 1 element to the array every click, that should hold these value, so that it after three clicks looks like this:
Click 1:
listObject[0]['listObjectName'] = 'Name 1';
listObject[0]['listObjectDesc'] = 'Desc 1';
Click 2:
listObject[1]['listObjectName'] = 'Name 2';
listObject[1]['listObjectDesc'] = 'Desc 2';
Click 3:
listObject[2]['listObjectName'] = 'Name 3';
listObject[2]['listObjectDesc'] = 'Desc 3';
The function:
$('#addListObjectSubmit').click(function (e) {
var listObjectName = $('#m_newListObject').val();
if((listObjectName == null) || (listObjectName == '')) {
return false;
}
else {
listObjects['listObjectName'] = listObjectName;
var listObjectDesc = $('#m_newListObjectDesc').val();
if ((listObjectDesc == null) || (listObjectDesc == '')) {
listObjects['listObjectDesc'] = null;
}
else {
listObjects['listObjectDesc'] = listObjectDesc;
}
}
e.preventdefault();
});
So, what is the best way of dealing with this?
It will help you a bit if you forget about associative arrays. They only theoretically exist in Javascript. In fact, everything is an object, even arrays. But thinking in data storage terms, you can use a simple array that can only be indexed numerically, or you can use an object as a data map.
The following example creates an array (note the more compact [] instead of new Array()) and pushes a map (created with {}) into it:
var listObjects = [];
...
var newElem = {
'listObjectName' : 'Name 1',
'listObjectDesc' : 'Desc 1'
};
listObjects.push(newElem);
Afterwards, you can access this element with listObjects[0], if it was the first element in the array.
If you want to access its properties, you can use one of these:
listObjects[0].listObjectName
listObjects[0]['listObjectName']
So you can see that when dealing with objects, you can use the . notation as well as the bracket notation - they are equivalent, but the latter form makes it look like it is an "associative array" (even more for people coming from PHP).
..you mean, you want to add an "associative array" (they're called "objects", in JavaScript, btw) to an array on each click?
The method to add things to arrays is push():
listObject.push({
'listObjectName': 'Name X',
'listObjectDesc': 'Description X'
})

Categories

Resources