How can I convert an array of numbers in javascript to string? - javascript

Like I have var arr = [1,2,3,4,5], I want this to become arr["1","2","3","4","5"]. I tried using:
var x = arr[0].toString(); //outputs "1"
but when I do typeof x it outputs "number".
How can I convert this that when I do typeof it will output "string"?

Most elegant solution
arr = arr.map(String);
This works for Boolean and Number as well. Quoting MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
As for VisioNs answer, this only works for browser that support Array.prototype.map

One way is to use Array.prototype.map():
var arrOfStrings = arr.map(function(e) { return e + ""; });
Check the browser compatibility and use shim if needed.

Probably a more elegant way of doing this but you could loop the array and convert each value to a string by adding it to a blank string +="". Check here for javascript type conversions
var arr = [1, 2, 3, 4];
for(var i=0;i<arr.length;i++) arr[i]+="";
alert(typeof arr[0]) //String

You can also use:
arr.join().split(',');

You can do it like this too: LIVE DEMO (if you want to use .toString())
var arr = [1, 2, 3, 4];
var i = 0;
arr.forEach(function(val) {
arr[i] = val.toString();
console.log(typeof(arr[i]));
i++;
});

Related

(Javascript) Finding multiple parameters between each other within a user input [duplicate]

I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?
e.g : var strVale = "130,235,342,124 ";
? "123,87,65".split(",").map(Number)
> [123, 87, 65]
Edit >>
Thanks to #NickN & #connexo remarks!
A filter is applicable if you by eg. want to exclude any non-numeric values:
?", ,0,,6, 45,x78,94c".split(",").filter(x => x.trim().length && !isNaN(x)).map(Number)
> [0, 6, 45]
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
Live Demo
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map to convert them and applying them to one single push:
arr.push.apply(arr, strVale.split(",").map(Number));
just you need to use couple of methods for this, that's it!
var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});
the output will be the array of numbers.
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');
SEE HERE
You can split and convert like
var strVale = "130,235,342,124 ";
var intValArray=strVale.split(',');
for(var i=0;i<intValArray.length;i++{
intValArray[i]=parseInt(intValArray[i]);
}
Now you can use intValArray in you logic.
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2":
",1,0,-1,, ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]
To solve this, I've come up with the following fix:
",1,0,-1,, ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]
Please note that due to
isNaN("") // false!
and
isNaN(" ") // false
we cannot combine both filter steps.
This is an easy and quick solution when the string value is proper with the comma(,).
But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.
"123,234,345,"
So I suggest using push()
var arr = [], str="123,234,345,"
str.split(",").map(function(item){
if(item.trim()!=''){arr.push(item.trim())}
})
There are good solutions in this post but I would like to add one more. Instead of using filter and map I would suggest to use reduce to iterate through all the items just once.
Also I will compare it with the use of a regex looking for digits. Please evaluate which method fits your needs. Here are the examples:
const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1'
const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, [])
console.log(arrayOfNumbersA)
// => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers
// do work and if the number have characters before or after
// the numbers are removed from since they are treated like NaN.
// Note: in this case the comma is the delimiting each number that will be evaluated in the reduce
const arrayOfNumbersB = strA.match(/[\d.]+/g).map(Number)
console.log(arrayOfNumbersB)
// => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers
// are transformed to positives and if the number have characters before or after
// the numbers placed any way.
//Note: that in this case the regex is looking for digits no matter how they are separated.
// FYI: seeing all the steps using the reduce method
const arrayOfNumbersC = strA.split(',').reduce((acc, val) => {
if(val && !Number.isNaN(+val)) {
acc.push(+val)
}
return acc
}, [])
console.log(arrayOfNumbersC)
// => [1, 0, -2, 21, 8.1]
In order to also take string value and avoid crushing we can solve it this way
let strVale = "130,235,342,124 ";
let unformattedArray =strVale.split(',');
const formatArray = (unformattedArray) => {
if (unformattedArray.map(Number).includes(NaN)) {
return unformattedArray;
}
else {
return unformattedArray.map(Number);
}
}
//then every time we want to format we call our function to format for us
console.log(formatArray(unformattedArray));
// or asign a value
let foramttedArray = formatArray(unformattedArray);

Checkio Common Words Challenge: How do i continue?

I need your help since i'm stuck at the challenge from checkio.
What am i missing? I get back:
Your result:"one,two,three"
Right result:"one,three,two"
The Challenge:
You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
UPDATE
this is my code:
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
match.toString() doesn't change the value of match variable. You need to return it from the function.
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
Explanation
There are two kinds of methods.
Mutator Methods
The first kind changes the original variable. You don't need to reassign the variable in case of those methods. Some of them are reverse(), fill(), etc
Note: These methods are only for reference type(objects, array) not for value types(string, number, boolean).
const arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); //[4, 3, 2, 1]
Accessor Methods
The second type are those methods which doesn't change the original variables but it returns are new value which is used by assigning it to a variable using =.
Some of them are map(), filter() etc.
let arr = [1, 2, 3, 4];
arr.map(x => x * x); //This line has no impact at all
console.log(arr) //Nothing is changed
arr = arr.map(x => x * x); //This line changes 'arr'
console.log(arr); //[1, 4, 9, 16]
Now toString() is of second type(accessor method) type. Just calling that method never changes the original variable. You need to reassign or return according to your needs

Finding the hundreds/thousands/tens figure javascript

I have the following issue:
Lets say I have the number 2382 stored in a variable and I want to store the figures of that number in other variables, for instance I want a = 2, b = 3, c = 8, d = 2. Is there any way I can acomplish this ?
you can get array of elements from this,
for example:
a = 2382
a.toString().split('').map(function(d) { return parseInt(d) } )
//[2, 3, 8, 2]
You could use an array for the values, after converting to a string and splitting and then convert the string back to number.
var number = 2382;
splitted = number.toString().split('').map(Number);
console.log(splitted);

Split string in javascript into an array

I am using the eval() function to create an calculator, and as you know eval returns a string (I am referring to this tutorial), for example 20+30. What I want now is to split this string so I will have an array of data like [20,30,50] where the 20 and 30 are the operands and 50 is the result in this case.
What I did so far is:
var input = document.getElementById('screen');
var result= '20+30'; // as an example
var firstOperand = result.split('+', 1); //this is taking the first operand
What I really want is as I mentioned to turn my input value that is string "20+30" to an array: myArr = [20,30,50].
Any help?
Use the power of maps and reduce!
result = '1+2+3+4+5+6+7+8+9';
a = result.split('+').map(function(x){ return parseInt(x) });
b = a;
b.push(a.reduce(function(p, c) { return p+c; }));
// b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 45]
Btw you shouldn't use eval(), look into the Shunting-yard algorithm instead. Code examples for the algorithm can be found here at SO and at Rosettacode.
you can create the array passing to the split function only the separator.
var myArr = result.split('+');
now you need to add the result:
myArr.push("50");

How to convert comma separated string into numeric array in javascript

I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?
e.g : var strVale = "130,235,342,124 ";
? "123,87,65".split(",").map(Number)
> [123, 87, 65]
Edit >>
Thanks to #NickN & #connexo remarks!
A filter is applicable if you by eg. want to exclude any non-numeric values:
?", ,0,,6, 45,x78,94c".split(",").filter(x => x.trim().length && !isNaN(x)).map(Number)
> [0, 6, 45]
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
Live Demo
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map to convert them and applying them to one single push:
arr.push.apply(arr, strVale.split(",").map(Number));
just you need to use couple of methods for this, that's it!
var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});
the output will be the array of numbers.
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');
SEE HERE
You can split and convert like
var strVale = "130,235,342,124 ";
var intValArray=strVale.split(',');
for(var i=0;i<intValArray.length;i++{
intValArray[i]=parseInt(intValArray[i]);
}
Now you can use intValArray in you logic.
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2":
",1,0,-1,, ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]
To solve this, I've come up with the following fix:
",1,0,-1,, ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]
Please note that due to
isNaN("") // false!
and
isNaN(" ") // false
we cannot combine both filter steps.
This is an easy and quick solution when the string value is proper with the comma(,).
But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.
"123,234,345,"
So I suggest using push()
var arr = [], str="123,234,345,"
str.split(",").map(function(item){
if(item.trim()!=''){arr.push(item.trim())}
})
There are good solutions in this post but I would like to add one more. Instead of using filter and map I would suggest to use reduce to iterate through all the items just once.
Also I will compare it with the use of a regex looking for digits. Please evaluate which method fits your needs. Here are the examples:
const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1'
const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, [])
console.log(arrayOfNumbersA)
// => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers
// do work and if the number have characters before or after
// the numbers are removed from since they are treated like NaN.
// Note: in this case the comma is the delimiting each number that will be evaluated in the reduce
const arrayOfNumbersB = strA.match(/[\d.]+/g).map(Number)
console.log(arrayOfNumbersB)
// => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers
// are transformed to positives and if the number have characters before or after
// the numbers placed any way.
//Note: that in this case the regex is looking for digits no matter how they are separated.
// FYI: seeing all the steps using the reduce method
const arrayOfNumbersC = strA.split(',').reduce((acc, val) => {
if(val && !Number.isNaN(+val)) {
acc.push(+val)
}
return acc
}, [])
console.log(arrayOfNumbersC)
// => [1, 0, -2, 21, 8.1]
In order to also take string value and avoid crushing we can solve it this way
let strVale = "130,235,342,124 ";
let unformattedArray =strVale.split(',');
const formatArray = (unformattedArray) => {
if (unformattedArray.map(Number).includes(NaN)) {
return unformattedArray;
}
else {
return unformattedArray.map(Number);
}
}
//then every time we want to format we call our function to format for us
console.log(formatArray(unformattedArray));
// or asign a value
let foramttedArray = formatArray(unformattedArray);

Categories