JS merge duplicates in array into "[num]x string" - javascript

I'm sure that this already has a duplicate, but I couldn't find one because I had no idea on how to phrase this question. Basically, I have a JS array. The user can add items to it from a dropdown menu. This array is then fed into a textarea. The user can input the same value more than once. If they have two of the same string in the array, I would like to delete both and replace it with '2x string'. Also, if '2x string' and 'string' both exist, then they will be made into '3x string', etc, etc. Thanks in advance for answering. I really appreciate it. I tried to keep it as general as possible so that others with the same problem can get help from this too.
JS:
var newfish = 'foo';
var oldtextareacontent = 'foo';
var fish = new Array();
var fishformatted = new Array();
function addfish(){
//form is never submitted so as not to refresh page
oldtextareacontent = document.getElementById("stock").value;
newfish = document.getElementById("fish").options[document.getElementById("fish").selectedIndex].text;
fish.push(newfish);
fishformatted = fish.join("\n");
document.getElementById("stock").innerHTML = "Your stock:
" + fishormatted;
}

Related

Creating array with multiple objects Javascript from XML data

I have a problem approaching this problem and I'm unsure in how to solve it. My XML looks like this:
<Order>
<OrderLines>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
<ProductLine>
<ManufacturerArticleNo>ARTICLENUMBER</ManufacturerArticleNo>
<Serials>
<SerialNumber>
.
.
<SerialNumber>
</Serials>
What I want to do is create an array, and fill it with objects with articleNumber, serialnumbers. Where I'm stuck is getting all the serialNumbers from a node to the corresponding article number.
Edits after comments:
Expected output: An array filled with the objects with ArticleNumber, Corresponding serial number. One serial number = one object.
Current Code:
//Create Article List
var artList = [];
//Get articles
var nodeArticleNo = xmlDoc.getFirstNode('//ProductLine/ManufacturerArticleNo');
while(nodeArticleNo != null) {
var artNo = xmlDoc.getNodeText('//ProductLine/ManufacturerArticleNo');
//Get Serials
var nodeSerialNumber = xmlDoc.getFirstNode('//Serials/SerialNumber');
while(nodeSerialNumber != null){
var serialNo = xmlDoc.getNodeText('//Serials/SerialNumber');
artList.push({ArticleNumber: artNo, SerialNumber, serialNo});
nodeSerialNumber = xmlDoc.getNextNode(nodeSerialNumber);
}
nodeArticleNo = xmlDoc.getNextNode(nodeArticleNo);
}
This is how I have been trying to solve it but I hate the while in a while and it is not working as intended
Thank you!

Trying to use input from prompt as object value within a function

Please be aware that I have only learned how to use objects this morning, so this is mainly an exercise to play around with this.
I was able to set up an array with a list of students. Each student is an object with multiple properties. I was also able to add another property and value to each object within the array using a for loop.
What I'm trying to do now is prompt the user to enter an object name "student1, student2, etc." I'm trying to use the value of that prompt, saved as var studentSelected, in the function reportStudentInfo(info).
What does work: If i get rid of the variable "selectedStudent", and I specifically decide to put in an object value student1, student2, etc. it works as expected.
What I don't understand:
I'm guessing the value of the prompt changes to a string from the prompt and it seems to mess up the value of what the object is, even though the prompt input might be: "student1" the function isn't reading it as student1. It returns an undefined value for each of the object property values.
I really hope I asked a clear enough question. Thanks for any help.
Logan
link to JSFiddle: https://jsfiddle.net/lwood3499/aevsbrk8/
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
reportStudentInfo( selectedStudent.name + " : " + selectedStudent.test1 );
After
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
selectedStudent is a string entered at the prompt. It does not have name or test1 properties.
If selectedStudent object already exists, you can do
var selectedStudent.name = prompt("Which student do you want to see the results for Test #1?");
or
var studentName = prompt("Which student do you want to see the results for Test #1?");
Update:
var selectedStudent = prompt("Which student do you want to see the results for Test #1?");
var found = null;
for (var iter = 0; iter < list.length; iter++) {
if (selectedStudent == list[iter].name) {
found = list[iter];
break;
}
}
if (found) {
reportStudentInfo(found.name + " : " + found.test1 );
} else {
alert(selectedStudent + " not found");
}

How to generate an array of arrays in Javascript?

So given:
var person = {name: "", address: "", phonenumber: ""}
I want to create a loop to receive user input (until they decide they don't want to input anymore information and input nothing or click cancel). I'd also like to use the person object as a prototype.
So I guess an object just to store the name/address/phone number of an arbitrary number of people. My logic for this would be to dynamically add an entire array to an object for every iteration of my loop. My code looks something like this:
var person = {name: "", address: "", phonenumber: ""}
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
//move input into the person array.
//person to look like {name = "mike", address = "main", phone = "123456789"}
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}
I've been trying to dynamically generate something like this:
customer =
[{name, address, phone},
{name, address, phone},
{name, address, phone}]
and then be able to access it and print it. i've been trying to access it with
console.log(customer[0].phone);
unfortunately im getting an error.
sorry for my error, console.log prints nothing so it seems like there's nothing stored in customer[0].phone.
i can't get access to any of the data that i've prompted the user for and saved in variables. when i use the alert function all i get is a blank box. whenever i try to print customer i get the message [object Object]or something along those lines
var customer = [];//create array
var person = {};// create object
var input = prompt("...");//your prompt
var results = input.split(", "); //create an array from the input
person.name = results[0];//add result with 0 index
person.address = results[1];//add result with 1 index
person.phone = results[2];//add result with index 2
customer[0] = person;//add the person object to the array.
The above code should do as you wish. I'm having a hard time seeing why you would iterate a prompt to the same user?? So try this first then go on.
http://jsfiddle.net/zkc2swmp/1/
Don't go irratating your users with prompt boxes, use a form. Also don't iterate something like that, and your condition in the for loop basically creates an infinite loop which is also bad
My code could be a lot better, such as if conditions, and exactly how to use this with a form. Though frankly it seems as though you are far from that. So I've started you off, try it and see if you can implement this the way you want, then comment with suggestions for helping you do something else.
First of all, every time you are assigning person to customer i.e.
customer[i] = person;
all other objects are getting modified as your breaking point is input== "" so all objects are modified with null values.
in start you are defining property as "phonenumber" and in the end u r putting value in "phone".
correct code shud be :
var customer = []; //used to store each person
var input = "x";
//loop prompting user to input name/address/phone number
for(var i = 0; input != ""; i++){
var input = prompt("Input separated by commas");
//example input: mike, main, 123456789
var results = input.split(", "); //create an array from the input
var person = {};
person.name = results.shift();
person.address = results.shift();
person.phone = results;
customer[i] = person;//store the person array into the customer array.
}

minimized code for arrays in js

I have three arrays in js and now i want to add empty check on them..so please help me in short/ minimized code for the empty array check.My js code is
var selectedfirst = jQuery('select#frsts').val();
var selectedsecond = jQuery('select#secnds').val();
var selectedthird = jQuery('select#thirds').val();
var lastfindal = selectedfirst.concat(selectedsecond); // Array concatination
var getfinal = lastfindal.concat(selectedthird); // Array concatination
I know how can i process empty check on single array but due to contcatenation the code goes longer . i contcate first array to second then concate to third.I want to concate array when they are not empty. like selectedfirst.length > 0.if anyone not understand fully i will provide more detail on request.Thanks in advance
After working i fix the issue.I created new array like
var hege = [];
if (selectedfirst!== null) {
alert('not emtpy');
var hege = hege.concat(selectedfirst);
}
the same condition for other too.

javaqscript: 2d associative arrays 101

This is my first Q&A ever, so hopefully it's alright.
As someone who generally picks stuff up quickly, I found the information on this topic was sporadic and generally over complicated, with many people saying it simply couldn't be done. so here's it broken down very simply.
Take this scenario as an example, we have a number of form components (text boxes, buttons, etc.), all with a number of properties, all of which have values... and we want to store these in a javascript array.
Here's my tinkerings. This code doesn't explicitly answer a question, as no question was explicitly asked, however I hope you find it useful
For good measure, here also is a jsfiddle http://jsfiddle.net/cQ8Xc/
var $parent_arr = new Array();
var $child_arr = new Array();
//we can add the key => value pairs like so:
//(obviously they won't be done like this, more likely a loop for example)
//this works just fine $child_arr[$key] = $value;
$child_arr['Top'] = '12';
$child_arr['Left'] = '13';
$child_arr['Right'] = '14';
$child_arr['Bottom'] = '15';
//we can add the array to another array like so:
$parent_arr['component1'] = $child_arr;
//clear the array for reuse (note that it is obviously not nessecary to reuse the array)
$child_arr = [];
//refill it
//note that the child arrays don't have to be identical lengths or values
$child_arr['Height'] = '22';
$child_arr['Width'] = '23';
$child_arr['Colour'] = 'blue';
$parent_arr['component2'] = $child_arr;
//we can access the data like this:
alert($parent_arr['component1']['Top']);
alert($parent_arr['component2']['Colour']);
//these didn't work for me, you've likely seen them in other answers if you've been researching this topic
//alert(JSON.stringify($parent_arr['component1'], null, 4));
//alert(JSON.stringify($parent_arr['component1']));
//alert($parent_arr['component1'].join("\n"));
//the array can be looped over like so:
for(var component in $parent_arr) {
for(var propertyName in $parent_arr[component]) {
alert(component + '.' + propertyName + '=' + $parent_arr['component1'][propertyName]);
}
}

Categories

Resources