Joining numbers together with a string - javascript

I know that for an array join() can be used to produce what I am trying to accomplish here, but I am working with a string. What method would work with a string?
I want my output to look like "3 then 4 then 5 then 6 then 7", etc.
I've come close to getting what I am looking for but my current code adds an extra "then" at the end, which is not what I want:
let appendString = '';
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendString += (start++) + then;
}
console.log(appendString);
}
I do not want solutions, I just would appreciate being pointed in the right direction.

I will try to not spoil the fun for you.
Think of it like this. If you have an array that has all your numbers, can you join them using .join ?
Now the question will be how to initialise an array with the numbers you want.
Try looking into array initialisations.
Does this answer your question ?

You are right that with an array you can use join. The thing is that you can turn a series of sequential numbers to an array easily:
function countUp(start, end, then) {
let arr = Array.from({length: end-start+1}, (_, i) => start + i);
return arr.join(then);
}
console.log(countUp(1, 10, ' then '));

what about this?
let appendString = '';
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendString += (start++)
if(i<9){
appendString+=then
}
}
console.log(appendString);
}
or
let appendArray = [];
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendArray.push(start++);
}
console.log(appendArray.join(then));
}

Related

Bringing numbers to the front

(Javascript)
functionName(“2 plus 3 is = 5!”);
would produce following message in console:
235 plus is =
I am unable to bring the numbers to the front, I am a little stumped
function frontNum(str) {
let emptyArr = [];
let rev = str.split("");
let expression = /[\d]/g;
for(let i = 0; i < rev.length; i++) {
if (rev[i].match(expression)) {
emptyArr += rev.pop(rev[i]);
}
}
console.log(emptyArr + rev.join(''));
}
frontNum("2 plus 3 is = 5!");
Since this is your home work I won't give you the correct version, but give you some pointers instead:
your emptyArr is an array, but you are adding data to it as if it was a string.
take a look at this topic, your pop causing problems
you can use your expression to capture all the digits and remove them from the string without need converting the string into array and loop through it (it can be done with 2 lines of code)
a way todo that
'use strict'
function frontNum(str)
{
let s = ''
, n = ''
for (let x of str)
{
if (/[0-9]/.test(x)) n += x
else s += x
}
console.log( n + s.replace(/ +/g,' ') )
}
frontNum('2 plus 3 is = 5!')

Why won't this iterate?

I am trying to make this Pig Latin function (I just started coding 3 weeks ago, so go easy on me), and I can't figure out why I can't get the array made from .split(' ') and then iterated through to join back again. In the output I only get the first word. The code is below:
function pigLatin(str) {
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
if (str1[i].length <= 1) {
return str1[i];
}
else {
let first = str1[i].substring(0,1);
let word = str1[i].substring(1);
str = word + first + 'ay';
return str
}
}
}
console.log(pigLatin("This is a test"));
Keep in mind that I was considering adding regex and more else if statements, but I can't even get this to work yet. Any help is greatly appreciated.
You're returning too early. You should be adding each word to an array, and at the end of your loop you should concatenate the words in the array to form a new string which you should return. See my comments for how I altered your code:
function pigLatin(str) {
let r = [] // The array to build
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
if (str1[i].length <= 1) {
r.push( str1[i] ); // Add to end of array
}
else {
let first = str1[i].substring(0,1);
let word = str1[i].substring(1);
str = word + first + 'ay';
r.push(str) // Add to end of array
}
}
return r.join(' ') // Join strings in array and return new string
}
console.log(pigLatin("This is a test"));

javascript transform text array

I use a react component which work like this
<FontAwesomeIcon icon={faCoffee} />
it take a font awesome icon let say address-book it add fa before, delete hyphen and uppercase the first letter of each world.
address-book become faAddressBook
copyright become faCopyright
arrow-alt-circle-down become faArrowAltCircleDown
Is it possible to create a javascript function which take an array like this
["address-book","copyright","arrow-alt-circle-down"]
and transform it in an array like that
["faAddressBook","faCopyright","faArrowAltCircleDown"]
There are some ways to do it. Like using regular expression. However, your requirement is simple, so it can be easily done with JavaScript split method. Please check the following implemented function.
function formatArray(str)
{
str = str.split("-");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return 'fa' + str.join("");
}
var givenArr = ["address-book","copyright","arrow-alt-circle-down"];
for( var i = 0; i < givenArr.length; i++) {
givenArr[i] = formatArray(givenArr[i]);
console.log(givenArr[i]+ '\n');
}
You can do the following with Array's map() and forEach():
var arr = ["address-book","copyright","arrow-alt-circle-down"];
function upperCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var outPut = arr.map(function(item){
var temp = item.split('-');
var temp2 = [];
temp.forEach(function(data){
temp2.push(upperCase(data))
});
return 'fa' + temp2.join('')
})
console.log(outPut);
Looks like there's two essential steps here. First, we need to prepend fa onto each string, and second, we need to convert them from kebab-case to camelCase.
So just write a function for each of those conversions, then run your array through a map using each of them:
const kebabs = ["address-book","copyright","arrow-alt-circle-down"];
function kebabToCamel(str) {
return str.replace(/-(\w)/g, m => m[1].toUpperCase());
}
function prependFa(str) {
return "fa-" + str;
}
console.log(kebabs.map(prependFa).map(kebabToCamel))

How to format number to currency?

I currently doing formatting of number to currency but is not working on a collection of an array. I used javascript to use the Math.round function. I would like to know how properly use this function. I appreciate your suggestion. Thank you.
Array:
{
"data": [
[
"9812355000",
"23397000",
"13976000"
]
]
}
for (var x = 0; x < data.data.length; x++) {
for (var i0 = 0; i0 < data.data[x].length; i0++) {
dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === ""
? 0
: Math.round(data.data[x][i0])}</td>`;
}
}
Need to achieve:
9,812,355,000
23,397,000
13,976,000
To achieve the output you specified using your array, you can iterate though the digits backwards (meaning, starting from the last number and moving to the first number) and then inserting a comma after 3 digits. Some sample code could look like this:
for(let i = numberString.length - 1; i >= 0; i--) {
if (i % 3 === 0)
array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}
var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;
// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');
Or inline:
var formatted = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
You can use an Intl.NumberFormat().format(x):
function myFunction() {
var x = document.getElementById("value_unformated").value
var a = Intl.NumberFormat().format(x)
var text = "Currency format: " + a + "<br>";
document.getElementById("value_formated").innerHTML = text;
}
<input type="number" id="value_unformated" value="13528468">
<button onclick="myFunction()">Format</button>
<p id="value_formated"></p>

How to build a simple string from a multidimensional array?

Basically, I have a multidimensional array that I need to build into a simple string.
Quite an easy question, although it has been eating away at me for quite some time now since I can't seem to nail it.
Here is an example of how my array could look with just 3 questions within it:
[["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]]
For example, D.rows[0][0] would be "question1" and D.rows[2][3] would be "answer3", just to clarify.
Here is how it must be saved into a string as:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
Each element must have a comma between them, and each question must be separated by a line-break.
This is what I currently have that is not working:
var fullString;
for (i = 0; i < csvArray.length; ++i)
{
second = secondArray[i];
for (j = 0; j < second.length; ++j)
{
fullString += entry[j] + "'";
}
fullString += "\n";
}
Thanks in advance!
try this
var s,a=[["question1","answer1","answer2","answer3","answer4"],"question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
for(i=0; i < a.length; i++){
s=(s)?s+"\n\r"+a[i].join():a[i].join();
}
jsfiddle example
In your own example: since you are going straight to adding to fullString, it should have an empty string for value, otherwise you will end up with undefined in the beginning.
var fullString="";
this part second = secondArray[i]; should have been
var second = csvArray[i];
and in a same way this fullString += entry[j] + "'"; should have been
fullString += second[j] + ",";
one liner:
var result = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]].join('\r\n');
something like this:
var questionAnswerSet= { "question1" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
"question2" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
}
and access like this:
questionAnswerSet[0].answer2 // question one answer 2
questionAnswerSet[1].answer2 // question two answer 2
for (var i=0; i<yourArray.length; i++) { // iterate on the array
var obj = yourArray[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}
If you have an array as this...
var arr = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
then...
var strArr = arr.join(',');
var strLine = arr.join('\n'); // string with line breaks.
will do that for you.
if you want different strings for each question-answer block, then...
var strJoinArr = [], strJoinLines = '';
for(var i = 0; i < arr.length; i++){
strJoinArr.push(arr[i].join(','));
strJoinLines += arr[i].join(',')+ '\n'; // string with line break
}
then to access each section you can use indexes,
For example, strJoinArr[2] will return 'question3,answer1,answer2,answer3,answer4'
more on .join()
more on .push()
This might be your solution if you plan ot change separators or number of answers.
var array = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]],
string = "";
for (var i = 0; i <= array.length - 1; i++) {
string +=array[i].join(', ');
string += "\n";
}
Also, in the less readable but also effective way, for any object of this structure
string = array.join('\r\n');

Categories