Perform addition on string items inside an array - javascript

I am trying the following addition -
arr = ["12","15"];
let sum = arr[0] + 5;
console.log(sum)
It returns me 125 instead of 17. ( because 12 is a string ) I tried to convert this array into an array of numbers by using var string = JSON.stringify(arr).replace (/"/g,''); and then performing the addition but string[0] returns ' [ ' , for the obvious reason.
Is there a direct way to perform this addition?

Here you go:
arr = ["12","15"];
let sum = parseInt(arr[0]) + 5;
console.log(sum)
When any side of the + operation is a string then + operator does string concatenation in javascript

The easiest way to convert an array of strings to an array of numbers, is with .map(Number):
let arr = ["12","15"].map(Number);
console.log(arr);

Related

Square every digit in JavaScript - string * string become a number?

I am very new to JavaScript and still learning the fundamentals. I was completing a JavaScript challenge were i needed to square every number eg. 881 become 64641. My code is below which i am happy with but I have managed to get myself confused by overthinking.
When i do numArray[i] * numArray[i] as they are both strings does JavaScript automatically convert to a number in order for the numbers to square themselves. Did it turn it into a number - square the number - then turn back into a string again. Which is why i have to do Number(squareArray.join(''));
The reason i ask is I know that if you do string * number it turns to a number, i would if something similar happens. If I am wrong please can someone explain so I can understand.
let numArray = num.toString(); //turn number to a string
let squareArray = []; // create an array to save the new values of the string
for (let i = 0; i < numArray.length; i++) { // iterate through the string
squareArray[i] = numArray[i] * numArray[i]; // save the square of the number to the array
}
return Number(squareArray.join('')); // turn the array into a string and then into a number}
Few observations :
As you want to make a square of a number, why converting those into a string ? Keep it in number form.
As you want each square number element should concat beside each other. You can achieve that only by joining via Array.join('').
Suggestion : Use Array.map() to get square of each number.
Working Demo :
let numArray = [1,2,3,4,5];
const squareArray = numArray.map(item => item * item);
console.log(Number(squareArray.join('')));
Concise one-liner solution
const squareEveryNum = (num) => +Array.from(`${num}`, v => v * v).join("")
Array.from() creates a new shallow-copied Array instance from an iterable or array-like object. e.g Array.from("123") OR Array.from([2,4,5})
Second argument of Array.from() takes callback function to be called on each element of array.
Array.from('223', v => v * v) // [4,4,9]
.join() returns string by concatenating all elements of the array.
+ converts string to number.
Links Array.from(),
Array.join()
References don't have to be [numbers][question].
asd

How to add special characters through the number raw?

I have generated random number. So i want to add some specific places to special characters
As a example - nuzmo2b2yhougkpntd5srif0fdami12_f6gyve0acaddzmt_rbz0iwlizmioiwdmlj
This is the how to genarate random numbers.
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
As well as i tried to use splice but it doesn't work
let updatedkey = randomkey.splice(20 , 0 , "_")
This says splice is not a function!
.splice is not a method of string (MDN doc), so to use that, you should convert it to array of character using .split(''), then do .splice, then convert back to string using .join('')
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
let updatedkey = randomkey.split('')
updatedkey.splice(20, 0, "_")
updatedkey = updatedkey.join('')
console.log(updatedkey)
You can use JavaScript String slice() method:
let updatedkey = randomkey.slice(0, 20) + "_" + randomkey.slice(20);

How to turn all integers in an array into a single number? [duplicate]

How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
Javascript join() will give you the expected output as string. If you want it as a number, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");

How to convert an array of strings to float in Javascript

I have this array and it is formatted as string:
['6.35', '2.72', '11.79', '183.25']
The problem is that when I convert it to numbers (using - without double quotes )
array.match(/\d+/g).map(Number) || 0;
it changes the dots used for decimals to commas. Then I end up with this new array:
6,35,2,72,11,79,183,25
So, instead of having 4 items inside the array, now I have 8 items, as my delimiters are commas.
Any ideas of how I can convert this array without replacing the dots?
Assuming you have an array in a string format, you can use the following regex to match all the decimals and then use .map(Number)
const str = "['6.35', '2.72', '11.79', '183.25']",
array = str.match(/\d+(?:\.\d+)?/g).map(Number)
console.log(array)
\d matches only digits, it's the short for [0-9]. For example, in 6.35 \d+ matches 6 and then 35 separately and the dot is ignored. What you get in result is array containing those matches.
As suggested in other answers, use of match is redundant in your case and you can go with:
array.map(Number)
You could just map numbers.
var array = ['6.35', '2.72', '11.79', '183.25'],
numbers = array.map(Number);
console.log(numbers);
var num = ['6.35', '2.72', '11.79', '183.25'].map(num => Number(num));
console.log(num);
Number() mdn
Parse the values to float :
console.log(['6.35', '2.72', '11.79', '183.25'].map(i => parseFloat(i)));
If for some reason .map() doesn't work just use a loop :
var array = ['6.35', '2.72', '11.79', '183.25']
var x = 0;
var len = array.length
while(x < len){
array[x] = parseFloat(array[x]);
x++
}
console.log(array)
Map over the array with the Number function, it will handle the conversion:
console.log(['6.35', '2.72', '11.79', '183.25'].map(Number));
If you want commas in your numbers, then you must stick with a string representation.
See this SO answer about a similar problem with ChartJS.
var arr = ["6,35,2,72,11,79,183,25"]
var result=arr.map(Number);
result[]
typeof(result[])
I was having the same problem this is a solution i found
i had
x = "11,1.1,100,100,2,3333,99"
and i wanted
x = [11,1.1,100,100,2,3333,99]
here's my solution
x.toString().replace(/, +/g, ",").split(",").map(Number)

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Categories