jQuery add text before final element of an array - javascript

I have an array:
var countryArray = [];
That I'm dynamically inserting values to with click events:
(on click...)
countryArray.push("Australia");
and then finally appending to a div for output:
$('#summary-countries').append(countryArray+'');
So my output could be:
Australia,United Kingdom,Finland,Japan.
Is there any way how I could insert some text so that it would output as the following:
Australia,United Kingdom,Finland **AND** Japan.
Any help would be appreciated!

Here's one way:
var countries;
if( countryArray.length > 1 ) {
var last = countryArray.pop();
countries = countryArray.join(', ')+' and '+last;
}
else {
countries = ''+countryArray;
}
$( '#summary-countries' ).append( countries );

Yes, there is a way. You are relying on the built-in serialization of arrays, when you call .append(reasonsTravelling+'');. This converts reasonsTravelling into a string, which, by default is a comma separated list.
You have to use a for loop instead and go through all the items in the array. Once you find that the iterator is one before the last index, use the "And" instead of ",".
This fiddle should explain my idea: http://jsfiddle.net/v76Bf/

You can traverse through and array and find the last index and insert the text before the last value.
for (var i=0;i<countryArray.length;i++)
{
if(i==countryArray.length-1)
{
countryArray[i].join(,).push("And");
}
}

Related

Separate strings in an array in a certain order

I have a list that I took from a converted CHANGELOG.md file, and it looks like this:
["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"]
What I want to do is to separate each version into its own list, like this:
["[3.0.0]", "Features", "changes done in file"],
["[2.0.1]", "Bug Fixes", "fixed login"]
Obviously, because it's a changelog, there can be multiple features and multiple bugfixes in a single version, so I want to a piece of code that separates the code appropriately.
I tried using if (string.startsWith('[')) but i couldn't manage to fit it in a loop.
Any help is appreciated.
Here's something I came up with. The code basically loops through the input array and adds each string to a currentArray variable. Everytime it hits a [ it puts the currentArray into the output and clears currentArray. At the end it removes the first element as the first element of the output will always be an empty array (since the first element of the input starts with a [)
var input = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
var output = [];
var currentArray = [];
for (var i = 0; i < input.length; i++) {
if (input[i].charAt(0) == '[') {
output.push(currentArray);
currentArray = [];
}
currentArray.push(input[i]);
}
output.push(currentArray);
currentArray = [];
//Since it will take the first one, and put empty one, need to do last step.
output.splice(0, 1);
console.log(output);
// ["[3.0.0]", "Features", "changes done in file"],
// ["[2.0.1]", "Bug Fixes", "fixed login"]
Assuming that you're always working in sets of three, this is a quick and ugly approach
var data = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"],
items = [];
data.map( (el, idx) => {
var last = items.length;
if( idx % 3 === 0 ) {
items.push( [] );
last += 1;
}
last = items[ last - 1 ];
last.push( el );
} );
console.log( JSON.stringify( items ) );
Here's an alternative solution should you prefer it:
const arr = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
const newArr = [];
let tempArr = [];
arr.forEach(function(v, i) {
if(/^\[\d+.\d+.\d\]$/.test(v) && i > 0) {
newArr.push(tempArr);
tempArr = [v];
} else {
tempArr.push(v)
}
});
newArr.push(tempArr);
console.log(newArr);
This snippet loops through the items one-by-one. It uses two arrays, one to hold the final result and one to populate with items for the current version.
I am using a regex to check if the item contains one [ followed by a number, then a period, number, period, number and finally the trailing ]. This allows the other strings that are not version tags to contain that character.
If the current item is a version tag, we push tempArr (which contains the changes of the current version that we've previously filled in our loop) to our result array newArr. Then, we empty the tempArr and give it the starting value of the next version tag.
If it is not, we just push the current item to our temporary array.
It would be interesting to know if you were guaranteed to get this data in triplets, as your example seems to imply. If you knew this up front, there are many creative solutions that could emerge. For just creating a 2D Array, however, I like this approach (you can run this directly in node.js to try it out):
const original = ['[3.0.0]', 'Features', 'changes done in file', '[2.0.1]', 'Bug Fixes', 'fixed login']
function transformToChangeLog (originalArray) {
const changeLog = originalArray.reduce((newList, element) => {
element.charAt(0) === '[' // check for version string
? newList.push([element]) // If version string, then push a new Array containing that string
: newList[newList.length - 1].push(element) // If something else, tack it onto the last Array in the changelog list
return newList // whatever is returned in the reduce function is passed to the next iteration, allowing us to build this 2D array one element at a time.
}, [])
return changeLog
}
console.log(transformToChangeLog(original))
I hope that helps! I like the reduce Array method, because of it's versatility and succinctness.

Null Values in array of objects

I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});

concatenate string from divs with the same class

I have the following code.
function sendData(){
console.log($(".MultiFile-title").text())
}
And the result from multiple titles is:
file1.txtfile2.txtfile3.txt
What I need is the output to be
file1.txt, file2.txt, file3.txt
I believe the a FOR EACH loop would be best here but how would I write it to get the text from each div with the class name "MiltiFile-title" any help?
You could try:
function sendData(){
var result = [];
$('.MultiFile-title').each(function () {
result.push($(this).text());
});
result = result.join(', ');
console.log(result);
}
This creates a temporary array and loops through all the ".MultiFile-title"s on the page, pushing each items text onto the array.
After it's completed looping, it joins the strings together using the string ", " as glue.
You can try:
jQuery(".MultiFile-title").map(function(i, v){return jQuery(v).text().trim()});

Display elements in my 2d Array in Javascript

I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com

jQuery finding class name value from class array

I am trying to find the exact value of a class name containing the text iconGroup and I am able to get an array of class names using:
var chosenIconClassArray = $('.selectedGroupIcon').attr('class').split(/\s+/);
console.log(chosenIconClassArray);
$.each(chosenIconClassArray, function(index, item) {
console.log(item);
});
This gives a console output of:
["createAGroupIconList", "inlinelist", "ram", "left", "iconGroup20", "selectedGroupIcon"]
createAGroupIconList
inlinelist
ram
left
iconGroup20
selectedGroupIcon
I have tried something along the lines of this to find which iconGroup it is, but it didn't work:
if (item ^= 'iconGroup') {
console.log($(this));
}
The goal is to be able to tell that the class array contains the value iconGroup20 (or any number such as 1, 2, 3, 4, etc) which I can then add to another element to update it's icon.
How can I go about searching that array and then find which iconGroup class is in it?
Are you looking for something that finds classes on an item that match the format 'iconGroup##'? If so, try something like this:
function getIconGroup(class_array) {
var iconGroup = false;
$.each(class_array, function(index, item) {
if item.match(/^iconGroup[0-9]+$/) {
iconGroup = item;
}
});
return iconGroup;
}
Updated to act as a function so you can use getIconGroup(ChosenIconClassArray).
JavaScript has a String.indexOf method. It'll return the index of the string you give it, or -1 if the string wasn't found.
The following piece of code should give you the class you're hoping for.
var chosenIconClassArray = $('.selectedGroupIcon').attr('class').split(/\s+/),
foundClass;
$.each(chosenIconClassArray, function(index, item) {
if (item.indexOf('iconGroup') > -1) {
foundClass = item;
}
});
The variable foundClass should contain the full class.

Categories