How can I split this string of numbers with ranges? - javascript

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.

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'

What is the easiest method to add individual numbers in a string using javascript

I have some logic within an app that generating strings like the following:
"001"
"021"
"031"
I want to take the single string and split this and add the numbers in a basic efficient manner.
e.g for the second string above
021 - desired outcome would be split this to make the sum 0 + 2 + 1 = 3 - how do I split the string by each number using vanilla javascript?
Try this:
var array = "0123456";
var result = array.split("").reduce((acc, cur) => {return (+acc) + (+cur);},0);
console.log(result);
As Bucket said in the comments, this will split the string up into characters, then use array.reduce() to merge all the characters into one value by using an arrow function that converts them to numbers and sums them.
var str = "021";
var a = str.split(""); // converts the string into an array
var result = a.reduce((i, n) => {
return Number(i)+ Number(n)
},0);
console.log(result)
//result = 3
This is probably as efficient as you can possible make it, but it does not do any input validation:
var input = "0021031";
var zeroCode = "0".charCodeAt(0);
function sum(input) {
var result = 0;
for (var i = 0; i < input.length; ++i) {
result += input.charCodeAt(i) - zeroCode;
}
return result;
}
console.log(sum(input))
function mathAdd(s) {
// take input and split it by ''
// use a as the accumulator
// use v as the value
// add the value to the accumulator and start at 0
// return the value
return String(s).split('').reduce((a, v) => a + parseInt(v, 10), 0);
}
console.log(mathAdd("001"));
console.log(mathAdd("021"));
console.log(mathAdd("031"));
var result = 0;
var second = "021";
var arr = second.split("");
for(var i = 0; i < arr.length; i++)
result = +arr[i] + result;
console.log(result);
Adding Numbers in a String :-
function addNum(nums) {
let newnums = nums.split(',').map(Number);
sum = 0;
for(i=0; i<newnums.length; i++) {
sum = sum + newnums[i];
} return sum;
}
console.log(addNum("1, 2, 3, 4, 5, 6, 7"))

Cut JS string present in an array at every occurrance of a particular substring and append to same array

Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!
What I have:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
What I need:
["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$
Example:
difference.$.user.$.otherinformation should be parsed to contain:
difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.
Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.
How best can I take this to closure?
Current flawed implementation:
for(var i=0; i<array.length; i++){
// next, replace all array field references with $ as that is what autoform's pick() requires
// /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
array[i] = array[i].replace(/\.\d+\./g,".$.");
if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
console.log("Substring without .$. " + array[i].substring(0, array[i].indexOf('.$.')));
console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')));
}
}
// finally remove any duplicates if any
array = _.uniq(array);
A functional single liner could be;
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"],
result = array.reduce((r,s) => r.concat(s.split(".").reduce((p,c,i) => p.concat(i ? p[p.length-1] + "." + c : c), [])), []);
console.log(result);
You can use this function inside your array loop.
var test = "difference.$.user.$.otherinformation";
function toArray(testString) {
var testArr = testString.split(".")
var tempString = "";
var finalArray = [];
for (var i = 0; i < testArr.length; i++) {
var toTest = testArr[i];
if (toTest == "$") {
tempString += ".$"
} else {
if (i != 0) {
tempString += ".";
}
tempString += toTest;
}
finalArray.push(tempString)
}
return finalArray;
}
console.log(toArray(test))
I used a Regex expression to grab everything until the last occurrence of .$ and the chopped it, until there was nothing left. Reverse at the end.
let results = [];
let found = true;
const regex = /^(.*)\.\$/g;
let str = `difference.\$.user.\$.otherinformation`;
let m;
results.push(str);
while(found) {
found = false;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m.length > 0) {
found = true;
results.push(m[0]);
str = m[1];
}
}
}
results.push(str);
results = results.reverse();
// Concat this onto another array and keep concatenating for the other strings
console.log(results);
You will just need to loop this over your array, store the results in a temp array and keep concatenating them onto a final array.
https://jsfiddle.net/9pa3hr46/
You can use reduce as follows:
const dat = ["authentication.$.order", "difference.$.user.$.otherinformation"];
const ret = dat.reduce((acc, val) => {
const props = val.split('.');
let concat = '';
return acc.concat(props.reduce((acc1, prop) => {
concat+= (concat ? '.'+ prop : prop);
acc1.push(concat);
return acc1;
}, []));
}, [])
console.log(ret);
Actually recursion is unnecessary for this problem. You can use regular loop with subloop instead.
All you need is:
split each occurence in the array into substrings;
build a series of accumulated values from these substrings;
replace the current element of the array with this series.
Moreover, in order to make replacement to work properly you have to iterate the array in reverse order. BTW in this case you don't need to remove duplicates in the array.
So the code should look like this:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"];
var SEP = '.$.';
for (var i = array.length-1; i >= 0; i--){
var v = array[i];
var subs = v.replace(/\.\d+\./g, SEP).split(SEP)
if (subs.length <= 1) continue;
var acc = subs[0], elems = [acc];
for (var n = subs.length-1, j = 0; j < n; j++) {
elems[j * 2 + 1] = (acc += SEP);
elems[j * 2 + 2] = (acc += subs[j]);
}
array.splice.apply(array, [i, 1].concat(elems));
}
console.log(array);
Use a simple for loop like below:
var str = "difference.$.user.$.otherinformation";
var sub, initial = "";
var start = 0;
var pos = str.indexOf('.');
for (; pos != -1; pos = str.indexOf('.', pos + 1)) {
sub = str.substring(start, pos);
console.log(initial + sub);
initial += sub;
start = pos;
}
console.log(str);

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);

Javascript : String to a two dimesional Array

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"

Categories

Resources