convert string array to integer array - javascript

I have created an array:
var endFlowArray = new Array;
for (var endIndex in flowEnd) { // <- this is just some numbers
for (var i in dateflow) { // <- same thing
var check = $.inArray(flowEnd[endIndex], dateflow[i]);
if (check >= 0) {
endFlowArray.push(i);
flowEnd[endIndex] = null;
}
}
}
How can I convert a string array of:
["286", "712", "1058"]
to integer array like:
[286, 712, 1058]

var arrayOfNumbers = arrayOfStrings.map(Number);

Strings in the console are symbolized by wrapping them in quotes. By that fact, we can assume that i is a string. Convert it to an integer and it will no longer be a string and no longer have those quotes.
endFlowArray.push(+i);
Your "numbers" in flowEnd and dateFlow are actually strings, not numbers.

To convert entire array's data type we can use map():
let numberArray = stringArray.map(Number)

try this:
let numberArray = stringArray.map(el=>parseInt(el))

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

How to convert first index of each array in my Array of array from string to int?

Initial :
var a = [["1","John"] , ["2","Alex"]]
Expected :
var a = [[1,"John"] , [2,"Alex"]]
Appreciate advise on how to convert the array.
Array.prototype.map() and coercing the first index to integer of nested array could be converted to your expected one.
var a = [["1","John"],["2","Alex"]]
.map(item => [+item[0], item[1]])
console.log(a);
Note: Here + is coercing the string to integer.
You can use the forEach method and use parseInt to turn the index you want into an integer. Dont forget your comma to separate the index of the outter array
var a = [["1","John"], ["3","Alex"]];
a.forEach((innerArray)=> innerArray[0] = +innerArray[0]);
console.log(a)
Alternatively, you can use Array.map(), together with the Number() function, to carry out the type conversion.
const a = [['1', 'John'], ['2','Alex']];
const result = a.map(item => [Number(item[0]), item[1]]);
console.log(result);
Use parseInt() for each string that needs to be converted to integer.

Retrieving Digits into an Array - JavaScript

I am doing a JavaScript, trying to retrieve the user's numerical input, and store the input's digits as an array.
I managed to retrieve the user's input using DOM, but, how can I store the digits into an array?
If you want to obtain an array of numbers, one solution is to use Array.from method and map array items to numbers.
let number=1234;
let array=Array.from(number.toString()).map(Number);
console.log(array);
If you want to store singular digits, you could use .split('')
userInput = '42';
console.log(userInput.split(''));
what you can do here is simply:
userInput1 = '42';
userInput2 = '43';
const inputArray = [userInput1, userInput2]
For an array of number:
var input = "123456789";
var array = input.split('')
for(var i = 0; i <array.length; i++) { array[i] = +array[i]; }
console.log(array)
The operation +array[i] is just a quick way to do the number conversion.
If you want the array of chars remove the for loop from the code

Javascript : How do I call the array index of the string?

Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)
You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);
I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.
You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];

Categories

Resources