Javascript : String to a two dimesional Array - javascript

I have a javascript function which returns a string in the following format :
User,5
Group,6
I want this string to be converted into a two dimensional array like below, any idea how can I achieve it?
[['user,5],['Group',6]]

You have to split by line break or blank space and map to split by colon:
str.split("\n").map(function(e) { return e.split(',') });
EDIT: If you want the second one to be an integer, convert it using parseInt:
str.split("\n").map(function(e) {
var arr = e.split(',');
arr[1] = parseInt(arr[1], 10);
return arr;
});
Attention, you do have to have map installed for browsers that do not have support for ECMA Script 5 to maintain cross-browser compatibility. You can do that by adding this to your code
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that /*opt*/) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}

var myBigString= " ";
var str1 =str.split("\n");
var myarr;
for(var i=0;i<str1.length;i++) {
var str2 =str.split(",");
for(var j=0;j<str2.length;j++) {
myarr[i] = str2[j]
}
}

USE STRING SPLIT BY COMMA AFTER THAT,FOR EXAMPLE
VAR STR11="User,5";
VAR STR22="GROUP,6";
VAR STR=STR11.split(",");
VAR STR1=STR22.split(",");
var items = [[STR[0],STR[1]],[STR1[0],STR1[1]]];

Try this
function convert(s) {
s.split("\n").map(function(s1){
var splits = s1.split(",")
splits[1] = parseInt(splits[1])
return splits
}
}
*assuming your string returned from function to be "User,5\nGroup,6"

Related

Pushing first character at last and returning the string

I was trying to find out a way where I can push the first character to the last and return the rest of the string.
suppose like reverse("aeiou") should be able to return
eioua
iouae
ouaei
uaeio
function strR(str){
var a = str.split('');
var tmp =[];
a.map (item => {tmp.unshift(item)
console.log(tmp);
})
}
strR("aeiou")
aeiou
I tried a lot seems not working . If anyone can help me would be really appreciated.
let bla = "aeiou";
for (let i = 0; i < bla.length; i++) {
bla = bla.slice(1) + bla[0];
console.log(bla);
}
Try this! Alert data can print out wherever
function myFunction() {
var str = "aeiou";
var count = str.length;
for (i = 0; i < str.length; i++) {
var res = str.substring(0, 1);
var result = str.slice(1);
var data = result + res;
str = data;
alert(data);
}
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Just use substr to remove the first character and charAt to add it to the end.
var string = 'aeiou'
i=0
while (i < 10) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
Maybe you are looking for this.
let input = "aeiou";
let chunk = input.split("");
let output = [];
for(let i=0; i<chunk.length;i++){
let last = chunk.shift();
chunk.push(last);
output.push(chunk.toString().replace(/,/g, ''));
}
console.log("Output", output.toString());
Here is one liner using Array.from and slice methods.
const str = "aeiou";
const str_arr = Array.from(
new Array(str.length),
(_, i) => `${str.slice(i, str.length)}${str.slice(0, i)}`
);
console.log(str_arr);
there is a short and easier way for do that:
function FirstToEnd (str){
return str.substr(1) + str[0]
}
and for result all possible data:
function FirstToEndAllPossible(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
str = str.substr(1) + str[0];
result.push(str);
}
return result;
}
good luck :)
Try This:
var string = 'aeiou'
i=0
while (i < string.length-1) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
You can use like this. Calling Recursion - Works for all the Strings.
var InputStr = 'aeiou';
var i = 0;
var word = [];
function callqueue(InputStr, i)
{
StringLength = InputStr.length;
i = i+1;
if (i <= StringLength)
{
firstChar = InputStr.slice(0, 1);
remainStr = InputStr.substr(1);
word.push(remainStr+firstChar);
callqueue(remainStr+firstChar, i);
}
return word;
}
output = callqueue(InputStr, i);
console.log(output);
Try below code
function strR(str){
for (let i = 0; i < str.length-1; i++) {
str = str.substr(1)+str.charAt(0);
console.log(str);
}
strR('aeiou');
Your question is not quite clear. Hope the below solution works for you.
function strR(str){
var a = str.split('');
a[a.length] = a.shift();
return a.join('');
}
strR("aeiou")
/* or */
String.prototype.firstToLast = function() {
var a = this.split('');
a[a.length] = a.shift();
return a.join('');
}
"aeiou".firstToLast();
I find using an array for this kind of string manipulation a bit more readable.
In the function below, we start with splitting the string into an array.
The second step will be using the native .shit method which returns the first item in an array (in our case, the first letter) while modifying the Lastly, as we have the first character and the rest of the string we build them into a new array where we spread (...) the modified array and adding the first character at the end. The join('') method returns a string out of the new array.
function firstToLast (str) {
const split = str.split('');
const first = split.shift();
return [...split, first].join('');
}
Hopefully it's clear and helps with what you were trying to achieve
My go-to would be to use JavaScripts built-in array methods. You can break a string into an array of single characters using split with no parameters, and put it back together using join with an empty string as a parameter.
let word = 'sydney'
function rotate (anyword) {
let wordarray= anyword.split()
let chartomove = wordarray.splice(0, 1)[0]
wordarray.push(chartomove)
return wordarray.join('')
}
rotate(word) // returns 'ydneys'

Break the string in positions in javascript

I need to split the string according to the positions not a string array just single string. I wrote following code and works fine. But is there any way to do it handy manner ?
function breakString(str, postion) {
var newStr;
var arr = [], res = [];
arr = str.split("");
for(var i = 0; i < postion; i++){
res[i] = arr[i]
newStr = res.join("");
}
return newStr;
}
console.log(breakString("rasika", 3));
There are the 2 ways that I can suggest you to use for this task.
✓ Using slice() method.
✓ Using split(), slice() & join() methods in conjunction.
http://rextester.com/CNVUP86671
var name = "rasika";
console.log(name.slice(0,3)); // ras
console.log(name.split("").slice(0, 3).join("")); // ras
easy manner
var arr = "Rasika";
console.log(arr.substring(0,3));

How can I split this string of numbers with ranges?

I have a string of numbers like this:
var string= "1,2,3,4-8,15,17,18-21,22";
How can I split it into an array that forms: [1,2,3,4,5,6,7,8,15,17,18,19,20,21,22]
UPDATE:Okay, code coming up in just a bit... trying to get a jsfiddle up.
var mystring= "1,2,3,4-8,15,17,18-21,22";
var array1= mystring.split(",");
document.getElementById("output").innerHTML=array1;
var array2 = searchStringInArray ("-", array1);
document.getElementById("output2").innerHTML=array2;
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
So around here I got stuck and was thinking there should be a better way. I know you have to search the array for hyphen split strings. But I failed to get them into another array that i could then insert into the first array.
https://jsfiddle.net/08au43ka/
var string= "1,2,3,4-8,15,17,18-21,22";
var arr=string.split(",");
var crr=[];
arr.forEach(function(a){
brr= a.split("-");
if(brr.length==2){
var o=parseInt(brr[0]);
var p=parseInt(brr[1]);
for(var i=o;i<=p;i++)
crr.push(i);
}
else
crr.push(parseInt(brr[0]));
})
console.log(crr);
You could split first by comma, then by minus and reduce the whole to a new array with an inner loop for missing values.
var string = "1,2,3,4-8,15,17,18-21,22",
result = string.split(',').reduce(function (r, a) {
var b = a.split('-').map(Number);
do {
r.push(b[0]);
b[0]++;
} while (b[0] <= b[1]);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can just replace the ranges:
var string = "1,2,3,4-8,15,17,18-21,22"
var regexRanges = /(\d+)-(\d+)/g;
var getRangeValues = function(range, start, end) {
return Array(end - start + 1).fill(+start).map((x, i)=> x + i);
};
var result = JSON.parse('[' + string.replace(regexRanges, getRangeValues) + ']');
console.log(result);
var string= "1,2,3,4-8,15,17,18-21,22";
var chunks = string.split(",");
var numbers = [];
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
if (chunk.indexOf('-') < 0) {
numbers.push(parseInt(chunk));
}
else {
var pair = chunk.split('-');
for (var j = pair[0]; j <= pair[1]; j++) {
numbers.push(parseInt(j));
}
}
}
console.log(numbers);
Since there is no known method for me to achieve what you want most likely you will need to write your own.
I'd split that string by commas, then i'd iterate through array looking for anything containing dash in it, if it contains dash grab that array item, parse it
get left side, get right side, create loop from i = left to i<right, push items into original array.

Split string into array by several delimiters

Folks,
I have looked at underscore.string and string.js modules and still can't find a good way to do the following:
Suppose I have a query string string:
"!dogs,cats,horses!cows!fish"
I would like to pass it to a function that looks for all words that start with !, and get back an Array:
['dogs','cows','fish']
Similarly, the same function should return an array of words that start with ,:
['cats','horses]
Thanks!!!
You can use RegEx to easily match the split characters.
var string = "!dogs,cats,horses!cows!fish";
var splitString = string.split(/!|,/);
// ["dogs", "cats", "horses", "cows", "fish"]
The only issue with that is that it will possibly add an empty string at the beginning of the array if you start it with !. You could fix that with a function:
splitString.forEach(function(item){
if(item === ""){
splitString.splice(splitString.indexOf(item), 1)
}
});
EDIT:
In response to your clarificaiton, here is a function that does as you ask. It currently returns an object with the values commas and exclaim, each with an array of the corresponding elements.
JSBin showing it working.
function splitString(str){
var exclaimValues = [];
var expandedValues = [];
var commaValues = [];
var needsUnshift = false;
//First split the comma delimited values
var stringFragments = str.split(',');
//Iterate through them and see if they contain !
for(var i = 0; i < stringFragments.length; i++){
var stringValue = stringFragments[i];
// if the value contains an !, its an exclaimValue
if (stringValue.indexOf('!') !== -1){
exclaimValues.push(stringValue);
}
// otherwise, it's a comma value
else {
commaValues.push(stringValue);
}
}
// iterate through each exclaim value
for(var i = 0; i < exclaimValues.length; i++){
var exclaimValue = exclaimValues[i];
var expandedExclaimValues = exclaimValue.split('!');
//we know that if it doesn't start with !, the
// the first value is actually a comma value. So move it
if(exclaimValue.indexOf('!') !== 0) commaValues.unshift(expandedExclaimValues.shift());
for(var j = 0; j < expandedExclaimValues.length; j++){
var expandedExclaimValue = expandedExclaimValues[j];
//If it's not a blank entry, push it to our results list.
if(expandedExclaimValue !== "") expandedValues.push(expandedExclaimValue);
}
}
return {comma: commaValues, exclaim: expandedValues};
}
So if we do:
var str = "!dogs,cats,horses!cows!fish,comma!exclaim,comma2,comma3!exclaim2";
var results = splitString(str)
results would be:
{
comma: ["comma3", "comma", "horses", "cats", "comma2"],
exclaim: ["dogs", "cows", "fish", "exclaim", "exclaim2"]
}

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

Categories

Resources