So, I have an input, I enter words for filter answers.
My answers are my panel.
I create an Array for register my answers.
var array = [];
But when I finish my loop, I want to innerHTML my datas who are in my Array.
But I have a [object HTMLDivElement] because i push Object in Array.
Ok my question is = How can I create an Array Object and push my panel in
var obj = {}
And How can I display them
This code search in answer if the words exist
if (searchIndex > -1) {
If the answer exist , push the panel in my array and count how many answer he founds
array.push(panel);
countFound++;
}
When the loop is finish, exploit this data and display them
array1.forEach(function(element) {
// I dont know how is the method to exploit all data one by one
});
Depending on what your HTML looks like, you should use innerHTML attribute to get the contents of an element.
array.push(panel.innerHTML);
You get the object HTMLDivElement because that's what panel is.
If you want to iterate over the elements in array you can do it with a foor loop, alternative with a foreach loop, and to display it again in the HTML you once again need to use the innerHTML attribute.
text = "";
for (i=0; i < array.length; i++) {
text += array[I];
}
document.getElementById("result").innerHTML = text;
And of you want to repeat the procedure you need to empty the array variable afterwards:
array = []; // Add this line after appending your data to the HTML.
// Realistically after the for loop
For more Details go to adding-elements-to-object
Here is how it works:
var element = {}, cart = [];
element.id = 1;
element.panel = document.getElementById("panel");
cart.push(element);
alert(cart[0].panel);
<div id="panel"></div>
Related
new to JS and I'm trying to append all the elements of an array to one string or element. I have tried a few different things but to no luck.
for (let i = 0; i < data.foodlist.length; i++) {
const foodlist_obj = data.foodlist.item[i];
console.log(foodlist_obj)
}
This returns a list like so:
Apple
Banana
Orange
Grapes
etc
But I would love to get the list to be like "Apple, Banana, Orange, Grapes, etc".
I have tried to use append and a few other options but cant seem to figure it out any help is appreciated
This returns a list like so:
It does not return a list. const foodlist_obj is a local variable within the for loop and as such it's being reset at every iteration. What is logged is a single string variable 5 times.
You need to declare the variable outside the loop as an array, then append to it.
const foodlist_obj = [];
for (let i = 0; i < data.foodlist.length; i++) {
foodlist_obj[foodlist_obj.length] = data.foodlist.item[i];
}
console.log(foodlist_obj)
Use Array#join to concatenate the items:
const data = {foodlist:['Apple', 'Banana', 'Orange', 'Grapes']}
const joined = data.foodlist.join(", ");
console.log(joined);
if you want to get them as string you can use toString() method
const foodlist_obj = data.foodlist.toString()
also you can use join() to replace comma separate with any other thing like new line
const foodlist_obj = data.foodlist.join("\n")
if you wants to get them as text with a special syntax you can create a variable called text and set it's type to string then add the array elements when loop
var text = "";
for (let i = 0; i < data.foodlist.length; i++) {
text += data.foodlist[i] + " item number("+i+")\n";
}
console.log(text)
if you get error that's will be of you because in your code you looping through data.foodlist but when you called the array you called him as data.foodlist.item[i] how do you called item property when you looping through data.foodlist you should call it like that data.foodlist[i] so check your array good first before loop
also you testing the foodlist_obj when you still loop and that's shouldn't give you something except one item in each iteration
also you used const to decalre your variable but const is unchangeable variable it's take just the first value assigned to it there's some cases when you can push items to const but you can't assign then add new items to const as text
The following code deletes all children of a certain element, besides these listed inside the saved variable.
let rightCol = document.querySelector("#rightCol");
let saved = rightCol.querySelectorAll('._4-u2._3-96._4-u8');
let savedArr = [];
saved.forEach(()=>{
savedArr.push(saved);
});
rightCol.innerHTML = ''; // Delete all children before retrieving "saved" ones.
for (var i = 0; i < savedArr.length; i++) {
rightCol.appendChild(savedArr[i]);
};
The code fails with this error:
TypeError: Argument 1 of Node.appendChild does not implement interface Node.
Why the code fails?
The code you presented have 2 errors:
querySelectorAll should be executed on document.
you are pushing entire array in for each loop.
here is the working copy
let rightCol = document.querySelector("#rightCol");
let saved = document.querySelectorAll('._4-u2._3-96._4-u8');
let savedArr = [];
saved.forEach((s)=> {
savedArr.push(s);
});
rightCol.innerHTML = ''; // Delete all children before retrieving "saved" ones.
for (var i = 0; i < savedArr.length; i++) {
rightCol.appendChild(savedArr[i]);
};
You are pushing your collection array for each element in your selection return instead of the elements
Where your code state .each(()=> on the next line, the argument to push should be this
On each iteration of forEach you are adding the entire saved array to savedArr. You should instead add each item using the parameter passed into the forEach callback.
e.g.
saved.forEach((s)=> {
savedArr.push(s);
});
Not sure why you're copying the array over to another array here though..
So, I have this function that, after an update, deletes elements from a table. The function, lets call it foo(), takes in one parameter.
foo(obj);
This object obj, has a subfield within called messages of type Array. So, it would appear something like this:
obj.messages = [...];
Additionally, inside of obj.messages, each element contains an object that has another subfield called id. So, this looks something like:
obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];
Now, in addition to the parameter, I have a live table that is also being referenced by the function foo. It uses a dataTable element that I called oTable. I then grab the rows of oTable and copy them into an Array called theCurrentTable.
var theCurrentTable = oTable.$('tr').slice(0);
Now, where it gets tricky, is when I look into the Array theCurrentTable, I returned values appear like this.
theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];
The loop below shows how I tried to show the problem. While it works (seemingly), the function itself can have over 1000 messages, and this is an extremely costly function. All it is doing is checking to see if the current displayed table has the elements given in the parameter, and if not a particular element, delete it. How can I better write this function?
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
var deletionPending = true;
for(var x = 0; x < theReceivedMessages.length; x++){
var messageID = theReceivedMessages[x].id;
if(diplayID == messageID){
console.log(displayID+' is safe...');
deletionPending = false;
}
}
if(deletionPending){
oTable.fnDeleteRow(idx);
}
}
I think I understand your problem. Your <tr> elements have an id that should match an item id within your messages.
First you should extract the message id values you need from the obj parameter
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });
This will give you all the rows ids you need to keep and then join the array together to use jQuery to select the rows you don't want and remove them.
$('tr').not(ids.join(',')).remove();
Note: The Array.prototype.map() function is only supported from IE9 so you may need to use jQuery.map().
You could create a Set of the message ID values you have, so you can later detect if a given ID is in this Set in constant time.
Here is how that would look:
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
// Now you can skip the inner loop and just test whether the Set has the ID:
if(!ids.has(displayId)) {
oTable.fnDeleteRow(idx);
}
});
So now the time complexity is not any more O(n.m) -- where n is number of messages, and m the number of table rows -- but O(n+m), which for large values of n and m can make quite a difference.
Notes:
If theCurrentTable is not a true Array, then you might need to use a for loop like you did, or else use Array.from(theCurrentTable, function ...)
Secondly, the implementation of oTable.fnDeleteRow might be that you need to delete the last rows first, so that idx still points to the original row number. In that case you should reverse the loop, starting from the end.
So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.
Hello I have a piece of code that checks a value against an array and if that value is not found in the array, then it adds that value to another array (called the soldListingArray). It then saves the soldListingArray to the localStorage (using localStorage.setItem("array", soldListingArray). For some reason, in my console I can see that the variable is the correct one, after adding it to the array, but outside of the code when I call for the entire array, it says it's empty.
array1 is the array I'm checking all the values inside against the array2 array.
Here is my code:
function checkToSeeIfListingIsSold() {
var soldListingArray = localStorage.getItem("array");
var x = 0;
var y = array1.length;
do {
var index = array1[x];
if (array2.indexOf(index) == -1) {
// Here I add the variable to my soldListingArray
soldListingArray[soldListingArray.length] = index;
// Here my console says what has been added to the soldListingArray (the value is correct).
console.value += index + " has been added to soldListingArray;\n";
}
x++;
} while (x < y)
localStorage.setItem("array", soldListingArray);
// Here I ask my console to display my soldListingArray but I get an empty array back.
console.value += "Sold Array: " + soldListingArray;
}
Why wasn't the index variable added and saved to my soldListingArray?
Any help is appreciated! Thanks in advance.
You need to convert the array to a string if you want to use local storage:
localStorage.setItem("array",JSON.stringify(soldListingArray))
Then when you need to access it later and add items, you convert it back to an array:
soldListingArray = JSON.parse(localStorage.getItem("array"));
This has been answered before; a little research would go a long way:
Storing Objects in HTML5 localStorage