count the number of characters in 1 format - javascript

I have a text whose type is string and not array, as shown below:
'[123,456],[789],[10]'
I want the count of number of arrays in this string(in this case it will be 3)
I want the number of elements in each array.
I can't use split with commas because there are commas between the numbers in that "array".
And I need to determine the length of those 3 arrays, how do I do that?
Desired result:
array: 3
length: 2,1,1

You could add an array in the string so you end up with an actual json array.
Then you can parse the json and count them.
let value = '[' + '[123,456],[789],[10]' + ']';
let json = JSON.parse(value);
json.forEach((item, i) => {
console.log('length: ' + item.length)
});
console.log(json.length + ' items')

Related

Perform addition on string items inside an array

I am trying the following addition -
arr = ["12","15"];
let sum = arr[0] + 5;
console.log(sum)
It returns me 125 instead of 17. ( because 12 is a string ) I tried to convert this array into an array of numbers by using var string = JSON.stringify(arr).replace (/"/g,''); and then performing the addition but string[0] returns ' [ ' , for the obvious reason.
Is there a direct way to perform this addition?
Here you go:
arr = ["12","15"];
let sum = parseInt(arr[0]) + 5;
console.log(sum)
When any side of the + operation is a string then + operator does string concatenation in javascript
The easiest way to convert an array of strings to an array of numbers, is with .map(Number):
let arr = ["12","15"].map(Number);
console.log(arr);

Split string by "/" and get result in two last words JS

I have my url like https://app.asana.com/0/1154029233771298/1161783458298546; I need to get result like 1154029233771298/1161783458298546. Thanks in forward!
You can split the URL string by the / character and rejoin the last two elements by the same character:
function extractLastWords(url) {
return url.split('/').slice(-2).join('/')
}
var u = 'https://app.asana.com/0/1154029233771298/1161783458298546'
extractLastWords(u) // => "1154029233771298/1161783458298546"
var arr = str.split("/"); // create array of strings that are separated by '/'
var result = arr[arr.length-2] + "/" + arr[arr.length-1]; // concatenate last 2 indices
Or alternatively:
var result = str.split("/").slice(-2).join("/");
.split("/") - create array of strings from delimiter
.slice(-2) - get sub-array with only the last 2 elements
join("/") - concatenate all strings in array with delimiter

Matching increasing numbers

I need to match numbers in the strings in an array.
['peter1','peter2','peter4'] ==> [1,2,0]
I want to regex each string of the array /1/g for the first string, /2/g for the second string and so forth.
You don't need regexp for this--you're just looking to see if the string contains the index, which you can check with indexOf or includes.
const inputs = ['peter1','peter2','peter4'];
const output = inputs.map((str, i) => str.includes(i + 1) ? i + 1 : 0)
console.log(output);
You can use a map function to...
Extract the number via regex
Compare it with the current 1-based index to filter out-of-sync numbers to 0.
const a = ['peter1','peter2','peter4']
const b = a.map((s, i) => parseInt(/\d+/.exec(s).pop()) === i + 1 ? i + 1 : 0)
console.info(b)

Find out number of numbers present in a comma separated string of numbers in Javascript

I have a requirement to check if some given numbers are Pythogorean triplets.
The textbox accepts string of numbers in the below format:
3,4,5 (comma separated values)
If the user enters more than or three numbers an error alert is displayed. My team mate figure out a way to do this , but accidentally. How does the below method work?
function CheckNumbers(strnum){
var num = strnum.split(",")
if(num.length != 3)
{
alert(Enter exactly three numbers!)
return;
}
}
Should'nt it return the length of the string rather than the number of numbers?
As I read it, the input parameter strnum gets split by "," into an array, and num.length returns the length of the array.
No, The above code is right what it does is to break string in to an array and than return the length of that array
strnum = 1,2,3;
num = strnum.split(",") // num = [1,2,3]
num.length // 3
Your case is you are using a Number, and replace is associated to String.
Try to cast it before.
strnum = "1,2,3";
num = strnum.split(",") // num = [1,2,3]
num.length // 3

Convert String to JSON node.js

Very new to node.js, I have string returning from RPGLE (as400) program, I would like to return as JSON example below.
String
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
Would like to convert as below and send to application api
[{"orderid":144234,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.020","shipped":1,"received":1,"status":"BAD"},
{"orderid":999290,"workorder":"999290.030","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.040","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.050","shipped":1,"received":1,"status":"GOOD"}]
What would be the best practice and how?
You can accomplish this string conversion through a series of regular expressions and a little decision logic to determine string and numeric values.
var meh = "{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},";
meh = "[" + // enclose with []
meh.replace(/(\w+)(?=:)/g, '"$1"') // search for words followed by a colon
.replace(/,$/, '') // trim the ending comma
.replace(/:([\w.]+)/g, function(match, value){ // grab the values
return ':' + ( // ensure preceding colon is in place
isNaN(value) || value % 1 !== 0 ? // is it a non-float number?
'"' + value + '"' : // enclose with "" if not a non-float number
parseFloat(value) // parse if is number
);
})
+ "]"; // enclose with []
console.log(JSON.parse(meh));
You could parse the lines into valid javascript objects and then stringify them into JSON like this:
const s = `
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
`;
const array = s.trim().split("\n").map((line) =>
line
.slice(1, -2) // remove brackets and comma
.split(",") // break into individual key/value pairs
.map((pair) => pair.split(":")) // split key/value pairs
.reduce((result, [key, value]) => { // reduce pairs into an object
result[key] = value;
return result;
},{})
);
const json = JSON.stringify(array, null, 2);
console.log(json);
How is the RPGLE program creating the string? If it is doing it piece by piece, then the RPGLE program could probably add the quotes and format the numbers correctly.

Categories