I have an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);
Related
I have a 2D Array which contains special characters '/'. I just want to get rid of it without affecting other values including blank field.
my array looks like array = [['S1/L','S1/F',''],['S2/F','' ,'S3/F'],['MS/F','S1/H','S3/L']]
I want the result as Result_array = [['S1L','S1F','' ],['S2F','' ,'S3F'],['MSF','S1H','S3L']].
I did not find any matching answer to this question that I can refer to that is why I am posting it here.
I am assuming it is a string array of arrays.
this code works
array = [["S1/L","S1/F", ""],["S2/F","" ,"S3/F"],["MS/F","S1/H","S3/L"]]
var newArr = array.map((arr)=>{
return arr.map((ar)=>{
return ar.replace("/","");
});
});
console.log(newArr);
This is in place replacement:
for (var i in array)
for (var j in array[i])
array[i][j] = array[i][j].replace(/\//g, '');
I have an array that contains multiple strings. I need to store each string minus the first letter and then concatenate them into a sentence.
I am trying:
var missingFirstLetter = array[i].splice(1);
What I have found online guides me to believe this should work, but it doesn't work as intended.
You should slice (not splice!) each element of the array and then store it back into an array, which you can do with Array#map, which maps each element to a new value, in this case the string without the first letter:
var arrayNoFirstLetter = array.map(el => el.slice(1));
This will iterate through the array and map each element to a new string without the first letter and store the new array of strings into arrayNoFirstLetter. Make sure to use String#slice to get a section of a string, because there is not String#splice method. (maybe you mistook it for Array#splice?) Then you can use Array#join to join them with a delimiter (which is the string between each element when joined together):
var joined = arrayNoFirstLetter.join(""); //join with empty space for example
For example:
var array = ["Apples", "Oranges", "Pears"];
var arrayNoFirstLetter = array.map(el => el.slice(1)); // ["pples", "ranges", "ears"]
var joined = arrayNoFirstLetter.join(""); // "pplesrangesears"
Try this:
var a=["hHello","+-I-am","d-evil"];
var x;
var z="";
for(var i=0;i<a.length;i++){
x=a[i].substring(1);
z=z+x;
}
console.log(z);
Result is :
Hello-I-am-evil
Is it what you wanted?
var strings = ['string1', 'string2', 'string3'],
stringsNoFirstCh = [];
for(key in strings){ // Iterates through each string in an array
let string = strings[key];
var s = string.substring(1); // Gets a string starting from index 1, so omits the first char
stringsNoFirstCh.push(s); // Add to a new array: ['tring1', 'tring2', 'tring3']
}
var string = stringsNoFirstCh.join(''); // Transform to a string: tring1tring2tring3
When looking at set of characters I am trying to put each letter into a specifc order in an array. For Example: Given the Strings "cat" and "dog" I would want an array that contains [d,o,g,c,a,t], cat at the end of the array because it was read first.
Currently I have tried this:
However, when I try the code below assuming the strings are "cat" and "dog".
I get an array containing: [c,a,t,d,o,g]. Instead of push I have also tried .unshift but the array now reads: [g,o,d,t,a,c].
var chars = /^[a-z]$/;
var string = [];
function makeword(){
if(currentChar.match(chars)){
string.push(currentChar);
currentChar = getNextChar(); //Gets next Character in the String
makeword();
}
}
Is something like this possible in Javascript?
If I understood you correctly, you want to provide a list of strings, then have them show up in an array in reverse order, with each letter as an element of the array. The following function will do just that:
function makeWords() {
var arr = [];
for(var i = arguments.length - 1; i >=0; i--) {
arr.push(arguments[i]);
}
return arr.join('').split('');
}
so running makeWords('cat', 'dog') will result in ['d','o','g','c','a','t'].
It's a relatively simple code when a functional approach is used. The rest and spread operators are very handy both to collect the function arguments and to spread the characters of a word into an array.
var characterify = (...c) => c.reduceRight((a,b) => a.concat([...b]) ,[]);
document.write("<pre>" + JSON.stringify(characterify("cat","dog")) + "</pre>");
Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);
"Friendship SMS:$#|5825|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png"
how can spilt that array[0] and store into different array
am trying to nsmaxrange
var subStar="|#$:";
var sub=":$#|";
by using that variables how can spilt that string stored that string into different variables
thanks & regards
How about:
var myarr = array[0].split(":");
then
myarr [0] = "Friendship SMS",
myarr [1] = "$#|5825|#$"
myarr [2] = "4cing.com/mobile_app/uploads/pageicon/friendship.png"
extracting one number from myarr[1]:
myarr [1] = myarr[1].match(/\d+/)[0];
or
myarr [1] = myarr[1].match(/[0-9]+/)[0];
then trim each array member as necessary.
var reg = /(.+)\:\$#\|(\d+)\|#\$\:(.+)/
var somestring = "Friendship SMS:$#|5825|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png";
var youranswerarray = somestring.match(reg).slice(1);
You define a regular expression using subgroups to select the three portions you actually want from the text. Then you apply the match function to the string and you get an array with the matched string and the matched subgroups. You only want the subgroup so you throw away the matched string, the first element of the array, by taking a slice/copy of that array starting with the element in the 1 position.