Javascript: Failing to add text into Array - javascript

The problem I am having is that my text is not being added into the array for some reason. The code looks fine, but I can confirm it's not being added by having it print out the array.length.
<script>
function addradio(value)
{
var element = document.createElement("input");
var label = document.createElement("label");
var tele = document.getElementById("Telephone");
var selected_text = tele.options[tele.selectedIndex].innerHTML;
// Array uses to stop duplicate radio button
var countryArray = new Array();
// Used to check if country is already in array, defaults to false
var contain = new Boolean();
// Checks if text contains a "1", returns "-1" if it doesn't
var str = selected_text.indexOf("1");
// For loop to check if country name is already in the array
for(var i = 0; i <= countryArray.length; i++)
{
if(countryArray[i] == selected_text)
contain = true;
else
contain = false;
}
// If value is not empty and text does not contain a "1" and array doesn't contain specified country
if(value != "" && str == "-1" && contain == false)
{
// Creating the attributes for a radio button
element.setAttribute("type", "radio");
element.setAttribute("value", value);
element.setAttribute("name", "telephone");
label.appendChild(element);
label.innerHTML += selected_text + "<br>";
// Creating the radio button
var newradio = document.getElementById("fillme");
newradio.appendChild(label);
// Adds country into the array if its' not already there
countryArray.push(selected_text);
}
}
</script>
Can anyone identify the issue with my Array.push() function?

You create an empty array and then try to loop over it. Since it's empty it has no length, so loop will never run. At the end you push a value into array, but next time method runs the array starts empty all over again
I suspect you intent to use the same array and call the function several times, in which case you would need to declare the array outside of your function.
You could also get rid of the for loop and use indexOf() to see if value you want is in array.
// Move this outside function
var countryArray = new Array();
/* shorter syntax*/
var countryArray =[];
function addradio(value)...

Your for loop is incorrect. It's missing the last element in the array.
// For loop to check if country name is already in the array
for(var i = 0; i < countryArray.length; i++)
{
if(countryArray[i] == selected_text)
contain = true;
else
contain = false;
}

Instead of doing the following:
for(var i = 0; i <= countryArray.length; i++)
{
if(countryArray[i] == selected_text)
contain = true;
else
contain = false;
}
I find this easier:
if(!!countryArray.indexOf(selected_text) && countryArray.indexOf(selected_text) > -1)
{
//then item exist in array. You do not have to use the base bool operator, but secondary check.
}
So basically:
if(countryArra.indexOf(selected_text) > -1)
{
//it exist!
}

Related

Find matching elements in an array

I have an array like this {A1,B5,C6,A2,B7,C4};
I want to loop through the array and find the matching element and then do some manipulation in that match.
The match in the above array is A1 and A2, B5 and B7 and finally C6 and C4.
Below is what I have done so far:
var arr = {A1,B5,C6,A2,B7,C4};
for (i=0; i < arr.length/2; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably
{
for (j=i+1; j < arr.length; j++)
{
if(arr[i].charAt(0) == arr[j].charAt(0))
{
j=arr.length; //This is done to end the inner loop
Do something;
//if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this.
}
}
}
You will need to sort the array first to make it easier to find the matching pairs. Here is one way you can modify your code.
var arr = ['A1','B5','C6','A2','B7','C4']
arr.sort();
console.log("Sorted array : " + arr);
for (i=0; i < arr.length -1; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably
{
if(arr[i].charAt(0) == arr[i+1].charAt(0))
{
j=arr.length; //This is done to end the inner loop
console.log("Match found : " + arr[i].charAt(0));
//if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this.
}
}
You could create an object with all the matches, like so:
var arr = ['A1','B5','C6','A2','B7','C4'];
var setsOfMatches = {};
arr.forEach(function(currentItem) {
var firstLetter = [currentItem.charAt(0)];
if (setsOfMatches[firstLetter]) { //If we have a set for this letter already
setsOfMatches[firstLetter].push(currentItem); //Add this item to it
} else {
setsOfMatches[firstLetter] = [currentItem]; //Create the set
}
});
//console.log(setsOfMatches);
//{
// A:["A1","A2"],
// B:["B5","B7"],
// C:["C6","C4"]
//}
//Iterate through the sets of matches
for (var set in setsOfMatches) {
console.log("Set " + set + ": " + setsOfMatches[set]);
}

Get duplicate character in javascript

How to get duplicate character in JavaScript,
As like input:
aaabcccdeffa
Output:
a4bc3def2
Try this:
var str = "aaabcccdeffa"; // Original string
// We are going to create a key-value array to store the number of occurance
// per letter (eg. 'a' : 4, 'b' : 1 etc.)
var store = {};
// Next we loop through each letter in the string
for (var a in str) {
if (store[str[a]] == undefined) { // If this letter has not ben found before, we set the count to 1 (first occurance)
store[str[a]] = 1;
}
else { // else if the letter has been found, we increase the count by one
store[str[a]] += 1;
}
}
// At this point, we have a key value array that contains the count of each letter
// Next, we loop through this array to generate the new string
var newStr = ''; // Initialise new string
for (var char in store) {
newStr += char; // append the letter to the string
if (store[char] > 1) {
newStr += store[char]; // If the count is more than one, we want to show the number too, so we append the number to the string
}
}
Output will be in newStr
you can use a HashTable, which in javascript is done through an Object. This code works
function duplicateCharacters(str) {
//Create an empty object
var hashTable = {};
for(var i = 0; i < str.length; i++){
//Check if the character has already been registered
//If false, register it and link a 1 to it
//If true, increment the integer linked to it
if (hashTable.hasOwnProperty(str[i]))
hashTable[str[i].toString()]++;
else
hashTable[str[i].toString()] = 1;
}
var output = "";
//Go through the hashTable
for(var key in hashTable) {
//Concatenate the key
output += key.toString();
//If the character only appeared once, do not add it
if(hashTable[key] != 1)
output += hashTable[key].toString()
}
return output;
}
Here is the reference code which uses both jquery and Regular expression for calculating the frequency of the character.
// Variable Declaration with Source text
var sourceText="aaabcccdeffa";
var resultText="";
// Splitting the source text to array
var sourceTextArray=sourceText.split("");
var uniqueText = [];
//Fetches Unique text from sourceTextArray in order
$.each(sourceTextArray, function(i, el){
if($.inArray(el, uniqueText) === -1) uniqueText.push(el);
});
//Iteration with unique text array
$.each(uniqueText, function(i, el){
//Regular Expression approach to calculate frequency of character with source text
resultText+=(sourceText.match(new RegExp(el, "g")) || []).length>1?el+(sourceText.match(new RegExp(el, "g")) || []).length:el;
});
alert(resultText);
Working Example Here

iterate two arrays and perform AND / OR comparison = return true

Here is my current filter function (quite incomplete)
$('input:checkbox.types').click(function(){
filterMarkers();
});
function filterMarkers() {
var checked = [];
$('input:checkbox.types:checked').each(function(){
checked.push($(this).val());
});
checked.sort();
var andor = '';
var andor = $('[name="and-or"]:checked').val();
if(andor == 1) {
// and
console.log(checked);
for (var i = 0; i < markers.length; i++) {
var types = markers[i]['types'].split(",");
types.sort();
console.log(types);
}
} else {
// or
}
}
Here is an image of what I have so far.
http://snag.gy/rKSTA.jpg
Let us say this for simplicity.
A = checked checkboxes
B = array with values of current item in map marker iteration / current iteration marker
I was able to get the values of the checked checkboxes. I was also able to convert the comma delimited string of each marker into an array. I would like to be able to check if B contains ANY of A (OR) and be able to check that B must contain A (AND).
Any ideas?
Here is the page in question for those wanting a 'feel' for what I am trying to accomplish. Thanks!
https://www.cablework.co/company
This page outputs what I have currently to console.
Once I can figure this out, I will then be able to hide/show markers based on the result.
Here's an example function. You would run test on every marker against the types array.
http://jsfiddle.net/q1k6e74d/5/
function test(op,types,marker){
var pass;
if(types.length === 0 || marker.length === 0){
return false;
}
if(op==="and"){
pass = true;
for(var i in types){
if( $.inArray(types[i],marker) == -1 ){
pass = false;
}
}
}else{ //or
pass = false;
for(var i in marker){
if( $.inArray(marker[i],types) !== -1 ){
pass = true;
}
}
}
return pass;
}
var a = [1,4];
var b = [1,5];
console.log("test a",a,"and b",b,test("and",a,b));
console.log("test a",a,"or b",b,test("or",a,b));
Could be shorter but it's easiest to understand this way I think.

How to display the contents of an array after comma splitting it in Java Script

I am fairly new to Javascript and have been picking it up pretty quickly in the past few days, after staring at my code for hours and trying to figure out why it wasn't working the way I intended i figured i would post it here.
Anyways, so my question is how do I display the WHOLE content of an array after comma splitting it. My code is below. My code is only printing out the last number set that I input at the prompt.
Help would be highly appreciated.
var gradeinfo = new Object(); {
coursecode = new Array;
grade = new Array;
};
var changer = function (y) {
finalgradeinfo = new Array;
finalgradeinfo = y;
function newresults() {
var i = 0;
finalgradeinfo[i] = y;
i + 1;
}
return finalgradeinfo;
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = new Array;
entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
My function needs to include closure so if it looks entirely wrong i apologize in advance.
Help from this post
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
In changer() you're destroying and recreating the array after each input. I suggest moving the array declaration into the global scope so that you can just push elements to it in the changer() function:
Fiddle
var finalgradeinfo = [];
var changer = function (y) {
finalgradeinfo.push(y);
}
do {
var entry = prompt("Enter a course code and grade seperated by a comma");
if (entry != null && entry != "") {
var counter;
var entryvalid = entry.split(",");
changer(entryvalid);
x = true;
} else {
x = false;
}
} while (x != false);
console.log(finalgradeinfo);
Notes:
Declaring arrays as [] is preferred to new Array
Not sure if you're aware but the newresults() function and gradeinfo object aren't doing anything
Also, the counter doesn't do anything, and the x boolean is unnecessary because it's basically just checking for prompt input. Here is my approach and fiddle.
var finalgradeinfo = { // declare finalgradeinfo in the global scope
coursecode: [],
grade: [] }
, entry = '';
do {
entry = prompt('Enter a course code and grade seperated by a comma') || ''; // will set entry to '' if user hits cancel
if (entry == '') continue; // break out of iteration if string is empty
var entryvalid = entry.split(",");
finalgradeinfo.coursecode.push(entryvalid[0]);
finalgradeinfo.grade.push(entryvalid[1]);
} while(entry !== '');
console.log(finalgradeinfo);

Match any element of an array against another array

Using the following function, I am searching an array for the existence of a value;
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
function searchArray(arguments)
{
var o = {};
for(var i=0;i<arguments.length;i++)
{
o[arguments[i]]=null;
}
return o;
}
if (carType in searchArray(checkboxValues) )
//do something...
This condition works well when carType (which is an array itself) contains only one value but when carType contains multiple values such as,
var carType = ["large-car", "4WD"];
...then the function will return false.
To give some background, what I am trying to do is show or hide map markers (via Google Maps) based on certain conditions,
Automatic
Manual
Small Car
Large Car
4WD
Each of these values is represented as a checkbox. If "Automatic" and "Small Car" are selected, then only shown map markers who contain both those values.
If "Automatic", "Small Car" and "Large Car" are selected then only show values which match those selections.
This works if the carType array contains only a single value but as an individual vehicle may have more than one type as shown above, this is where the function fails.
What's the best way to write the function to allow for comparing multiple values in one array against that of another?
Snippet taken from this answer.
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
And then use it like this:
var checkboxValues = ['large-car', 'small-car', 'automatic'],
carType = ["large-car"],
merged = arrayUnique(checkboxValues.concat(carType));
if (merged.length === checkboxValues.length) {...}
If you need to return the matching elements of two arrays you can do this:
function matchArrays(base, toSearch) {
var returnArray = [];
for (var i = 0; i < toSearch.length; i++) {
if (base.indexOf(toSearch[i]) !== -1) returnArray.push(toSearch[i]);
}
return returnArray;
}
Usage:
var match = matchArrays(checkboxValues, carType); // return "large-car"
Take a look at array_intersect from PHPJS, a reproduction of PHP's array_intersect function in JavaScript.
You can use js functionality to match array.
One ways is to use indexOf() function that return the index of the string if it is found in array or -1 if not found.
var checkboxValues = ["large-car", "small-car", "automatic"];
var carType = ["large-car","automatic","some car"];
function searchMatch(carType) {
var result = new Array();
for(var i=0;i < carType.length;i++) {
// If match found push the match to the result array.
if(checkboxValues.indexOf(carType[i]) != -1){
result.push(carType[i])
}
}
return result ;
}
As a result you will get ["large-car","automatic"];
if you use underscoreJs may look like this
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ['small-car','automatic'];
var result=_.any(checkboxValues,function(checkbox){
return _.any(carType,function(carT){ return carT==checkbox;});
});
Try this jQuery solution:
<script type="text/javascript">
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
if ($.inArray(carType[0].toString(), checkboxValues ) == -1) {
return false;// if not exists
}
</script>

Categories