handling js arrays with jQuery - javascript

I am wanting to store some info in array
i declared an array
var added = [];
Question: I want to add a number/string at the last of the array.
And then i want to add all the data to the a dom ?
I am new to js array please help me out with this basic things

added.push("123");
added.push("abc");
$('div').html(added.join());
This will set the html of the div to 123,abc

added.push("123");
added.push("abc");
added.push("xyz");
for(i in added)
{
$("div").append(added[i]);
}
Hope this helps!
EDIT:
I though you need to assign all one by one!
You could use:
$("div").html(added.join(', '));
to get things seperated by comma!

Related

isbn de-duplicate with javascript/jquery

Brief background: I retrieve book info from google books and worldcat via each api. I parse through the data to create an html div outputs with stuff of interest for a webapp.
The problem: the isbns. After getting isbns from each, I merge them into one div. For example:
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
I would like to eliminate the duplicate isbn (e.g., 9781137012920) with either javascript or jquery. I can get the text of the span but every solution I have tried has failed thus far.
Any help - esp, with a codepen or fiddle - for this amateur would be greatly appreciated.
PS:I know variations of this question have been addressed on StackOverflow - and believe me that I am sick of duplicates! - but I have not managed to fix this after a couple of days of trying. Examples that type in the content as var work but how do I get it from the div and make it work?
Do something like this using text() method with callback
$('span').text(function(i, v) { // use callback to get old value
return v.split(' ') // split the old value
.filter(function(v1, i, arr) { // v1 is array element, i is index, arr is iterating array
return arr.indexOf(v1) == i; // filter unique value by checking the index
}).join(' ') // join and return the unique values
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
For more about finding unique array element refer : Remove Duplicates from JavaScript Array
I suggest removing the duplicates before making them into the div. If you are getting the values in an array you can eliminate the duplicates easily. Remove Duplicates from JavaScript Array
I think you want something like this :
var string = $('span').text();
var uniqueList=string.split(' ').filter(function(allItems,i,a){
return i==a.indexOf(allItems);
}).join(' ');
$('#output').append(uniqueList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
<h1>Input</h1>
<span>9781137012920 9780230339118 9781137012920 1137012927</span>
</div>
<div id="output">
<h1>Becomes</h1>
</div>

Deleting an element from JSON in javascript/jquery

I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the situation I'm in to.
{brands:[51,2046,53,67,64]}
Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.
Try to use Array.prototyp.splice,
var data = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);
Since you want to remove an element from an array inside of a simple object. And splice will return an array of removed elements.
If you do not know the position of the element going to be removed, then use .indexOf() to find the index of the dynamic element,
var elementTobeRemoved = 53;
var data = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);
You could write the same thing as a function like below,
function removeItem(arr,element){
return arr.splice(arr.indexOf(element),1);
}
var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);

Values of all textboxes on a page - without knowing the ID?

I am developing a Chrome Extension that, when the user leaves the page, saves all the text from the textboxes on that page and outputs it to a file.
If I knew the IDs of the textboxes on the page, then it wouldn't be a problem, but the issue is that I need the extension to get the values of all of the textboxes on the page without knowing the IDs, as it will be a different website each time the extension is used.
Also, how would the information be collected? In a string? It would be nice to go down the page and add each textbox to a file, one by one, instead of one huge string.
I've never used jQuery or understood it, and there's probably a solution in it staring me in the face. If anyone suggests using it, please could you explain it a little bit?
Thanks in advance. I would post my code, but I don't know where to start - ergo I don't have any.
you could store it in array using $.each, as :
var valsArr = [];
$("input[type=text]").each(function() {
valsArr.push( $(this).val() );
});
or create object with name as key and value as its value, like:
var valsObj = {};
$("input[type=text]").each(function() {
valsObj[this.name] = $(this).val();
});
You can do it like this:
function onClick(){
var areas = document.getElementsByTagName("textarea");
for(var i = 0; i < areas.length; i++){
alert(areas[i].value);
}
}
<textarea></textarea>
<textarea></textarea>
<button onclick="onClick()">Gather information</button>
Also see this regarding your "save to a file" question Using HTML5/Javascript to generate and save a file
Use the selector and apply it in an each cycle.
$(":text").each(function(){
alert($(this).val());
});
Make a for loop
for(i=0; i < $("input[type='text']").length; i++){
$("input[type='text']").index(i).value();
}
You can use .map() : It returns an array.
var arr = $(":text").map(function() {
return this.value
}).get(); //add join(',') after get() to get a simple comma separated list.
Instead of input[type="text"] you could also use :text pseudo selector.
Demo

How to add and remove elements of an Array

I want to maintain a list of things in javascript. This seems to be a non trivial problem in this language...
var things = []
// for adding:
things[things.length] = thing
// for removing:
delete (things[things.indexOf(thing)])
This kinda works, but I fear the adding is a bug. When a thing that is not at the end of the array gets removed, a following add operation will overwrite an existing element, right? Because length is the number of elements.
How to do the adding correctly? Or is there a better way to do this with plain javascript (no JQuery)?
I would recommend using push and splice. With push, you don't have to keep track of your last inserted index. Also, with splice, you actually remove the element from the array and you aren't just deleting the reference and making it null.
Something like this would work:
things.push(thing);
things.splice(index, 1);
For adding you want to use push, so things.push(yourThing);
Adding to an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Removing from an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
I would use a loop.
var index;
var things= [];
for (index = 0; index < things.length; ++index) {
text += things[index];
}

How to insert the new array values with previously inserted item at same array index

Lot of questions are available for array push and splice but not like this one.
Please see this fiddle for what i try
JS Fiddle
I have the output like this
[{"rup":"100","dol":"50"},{"rup":"100","dol":"50"},{"expense":
[{"reason":0,"cost":0,"receipt":0,"expense_type":0}]},{"expense":
[{"reason":1,"cost":1,"receipt":1,"expense_type":1}]}]
but what i need is
[{"rup":"100","dol":"50",{"expense":[{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50",{"expense":[{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]
I tried SPLICE() and ARRAY.INSERT() methods but not get like above.
Please suggest any ideas.
use this piece of code,
for (var i in costArray) {
costArray[i].expense = expenseArray[i];
}
Out put:
[{"rup":"100","dol":"50","expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50","expense":{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]
SEE THIS FIDDLE DEMO
The format you want in not valid in javascript, I guess you mean this:
{ "rup":"100","dol":"50", "expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0} }
To get this, try replacing
costArray.push({"expense":expenseArray});
with
costArray[i]["expense"] = expenseArray
in the second loop.

Categories