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);
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
The conundrum I have is as follows: I have an array of the pair of indexes of a string at which one character (the third item in the sub-arrays) must be inserted (note, these pairs can be duplicates), e.g.
let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];
let my_string = "This is a very important string";
for (let i = 0; i < arr.length; i++) {
// magic code
}
// => my_string now equals "7hth2is i7hs a 2vejry imjportant string";
I can't just insert the character at each index because the next pair of indexes in the array will become out of date, due to the previous pair of indexes changing the string and so causing it to have new indexes for each character.
I've also tried slicing the string based on the index pairs (using them as the start and end indexes) and inserting the characters onto these substrings before merging them all together again, but the issue with this is that if two pairs of indexes overlap, then parts of the original string get duplicated.
NOTE: the array is sorted in order from smallest second index in the pair to largest, as shown above. This can be changed. However, the array will always contain pairs of indexes - i.e. I cannot flatten the array into just indexes because of the third item of the arrays being the character I want to insert.
One other thing I tried was going from the end of the array of index pairs to the start, but again the fact that index pairs can overlap means this does not work.
How would I insert the characters at each index in the array of index pairs?
Thanks in advance for any help.
You could create an object of indicies containing strings, where each string item specifies the string to insert at that index. Eg, from
[[0, 6], [0, 6], [2, 10]]
and an array of characters to insert ['x', 'y', 'z'], construct
{
0: 'xy',
2: 'z',
6: 'xy',
10: 'z'
}
Then you can use a regular expression to match any position (without matching any characters), and use its callback function to look up the current index on the object, and replace with all the characters at that point (if any):
let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];
const obj = {};
for (const [left, right, char] of arr) {
obj[left] = (obj[left] || '') + char;
obj[right] = (obj[right] || '') + char;
}
const my_string = "This is a very important string";
console.log(
my_string.replace(
/(?:)/g,
(_, index) => obj[index] || ''
)
);
Instead of looping through the array you can loop through the string.
let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];
let my_string = "This is a very important string";
let str2 = ''
for (let i = 0; i < my_string.length; i++) {
str2 += arr.filter(x => x.includes(i))
.reduce(( total, current) => total + current[2],'') + my_string[i];
}
console.log(str2);
The filter will keep those elements in arr that contains the current index (i) of the loop.
If the filter's output is not empty then reduce will concatenate all their 3rd elements. Finally the current my_string element is added at the end.
If the filter's output is empty, reduce will do nothing, so only the current character in my_string is concatenated to str2.
The result:
7hTh2is i7hs a 2vejry imjportant string
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);
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");