I have array in txt file and read this with
fs.readFileSync("./input.txt")
When i wrap it in console.log i get(since it is written in the file itself):
1 2 3
100 5000
I would have the array:
['1','2','3','100','5000']
Placement of the array in the input file should not change.
Suggest how to do it, please.
You can use regex to split words: \w+
let a = ` 1 2 3
100 5000 `;
console.log(a.match(/\w+/g))
To read your file and split it:
fs.readFileSync("./input.txt").match(/\w+/g)
One way, load it then, split by lines, then on each line split by space then flatten it, then filter out empty values.
let str = `1 2 3
100 5000 0`; // added 0 to show filter(Boolean) wont remove
console.log(str.split('\n').map(v => v.split(' ')).flat().filter(Boolean))
Result:
[
"1",
"2",
"3",
"100",
"5000",
"0"
]
You could split the string by a space, then filter out the falsy items in the resulting array.
const input = ` 1 2 3
100 5000 `;
let res = input.split(" ").filter(e => e.trim())
console.log(res)
Related
In my nodeJs code I make a REST call to a 3rd party api and one of the values in the response is a string value e.g:
"total": "-15"
Note that this value can either be a negative number, zero or a positive number, but as a string.
e.g:
"total": "-5"
"total": "0"
"total": "+3"
How can I convert this value to be as follows? Based off the above example:
5 under
level par
3 over
I am quite new to node/javascript - is regex the best option to do this?
As Blunt Jackson said, regex will probably be slower. Here is a conversion function example:
const toText = (value) => {
const parsed = parseInt(value)
return parsed > 0 ? `${parsed} over` : parsed < 0 ? `${Math.abs(parsed)} under` : 'level par';
}
console.log(toText("-5"));
console.log(toText("0"));
console.log(toText("+3"));
I like this question because I like Code Golf :D
So my suggestion would be this one-liner:
const toText = v => v == 0 ? "level par" : v < 0 ? `${-v} under` : `${+v} over`;
console.log(toText("-5"));
console.log(toText("0"));
console.log(toText("+3"));
Works with Numbers or Strings as parameter.
I have a string as an input in the form; lets say "1,5;6,10". Now, I want to compare the number at position 1 and 3 .i.e.(1 & 6). Whichever one is largest the number right to it would be printed. In this case the number 10 would be printed as 1 < 6.
Let the input is,
const customer_demand ="1,5;6,10";
I want to procced with slice() method and separate 1 and 6 with:
const number1 = customer_demand.slice(0, 1); // 1
const number2 = customer_demand.slice(4, 5); // 6
and compare the resultants with if & else. But there may be a case when the third number is two digit like:
const customer_demand ="1,5;16,10";
my slice() method index would go offset. What can I do in this regard? I hope I have made myself clear, if not please leave a comment. Thanks
In your case it's better to use split:
const customer_demand ="1,5;16,10";
const number1 = customer_demand.split(";")[0].split(",")[0]; // 1
const number2 = customer_demand.split(";")[1].split(",")[0]; // 16
Also if you want them to be Numbers don't forget to cast it using parseInt.
The solution, use split. Here's an example
const customer_demand ="1,5;16,10";
function parseNumbers(string){
return string.split(";") //returns stuff like ["1,5", "16,10"]
.map(axis=>
axis.split(",") //["1", "5"]
.map(n=>parseInt(n)) //[1,5]
)
}
//example usage
const parsedDemand=parseNumbers(customer_demand)
const [number1,number2,number3,number4]=parsedDemand
console.log(parsedDemand)
Make your life easier and break up your strings into managable arrays. Here is an example of when you don't know how many sets of numbers to compare ahead of time.
const customer_demand ="1,5;16,10";
// the following should also work for data like: "1,3,4,7;1,44;100"
let answers = [];
customer_demand.split(";").forEach( set => {
let setitems = set.split(",");
let biggest = setitems.reduce(function(a, b) {
return Math.max(Number(a), Number(b));
});
answers.push(biggest)
});
// answers is now an array - each item is the biggest number of that set. In your example it would be [5,16]
For example, I have user input any string: "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. These are just examples, the user can input any string.
I want to map this to integer cardinality:
"1st" -> 0
"2nd" -> 1
"third" -> 2
"fourth" -> 3
"fifth" -> 4
"9999th" -> 9998
So I need some kind of function where:
function mapCardinality(input: string): number{
let numberResult:number = ??
return numberREesult;
}
and I can call it like this:
console.log(
mapCardinality("1st"), // print 0
mapCardinality("2nd"), // print 1
mapCardinality("third"), // print 2
mapCardinality("fourth"), // print 3
mapCardinality("fifth"), // print 4
mapCardinality("9999th") // print 9998
);
Just look it up in an array or parse it as number:
const mapCardinality = c => {
const pos = ["1st", "2nd", "third", "fourth", "fifth"].indexOf(c);
return pos === -1 ? parseInt(c, 10) - 1 : pos;
};
I'd first ask what are the suffixes for all of the inputs?
'nd', 'rd', 'st', 'th' (most numbers)
If they enter an integer with the above prefixes then you could write the following function:
const getInteger = input => input.slice(0, -2);
const num = getInteger('999th');
console.log(num); // prints "999"
If they enter the elongated variant, it becomes much more complex, especially when it comes to typos, lack of spaces, etc. One way could be to map single digit words ('one', 'two', etc), tens ('ten', 'twenty', etc'), hundreds, thousands, and so on instead of every number imaginable. I would then parse and find matching words to give a result. That being said it is still limiting. I would strongly suggest limiting user input formats. Why can't the user input an integer?
const cardinalDictionary = {
'zero': 0,
'one': 1,
...,
'twenty',
...,
'hundred': 100,
'thousand': 1000,
};
I have a set of text messages. Lets call them m1, m2, ..... The maximum number of message is below 1,000,000. Each message is below 1024 characters in length, and all are in lowercase. Lets also pick an n-gram s1.
I need to find frequency of all possible substring from all of these messages. For example, lets say we have only two messages:
m1 = a cat in a cage
m2 = a bird in a cage
The frequency of some n-gram in these two messages:
'a' = 4
'in a cage' = 2
'a bird' = 1
'a cat' = 1
...
Note that, as in = 2, in a = 2, and a cage = 2 are subsets of in a cage = 2 and have same frequency, they should not be listed. Only take the longest one that have the highest frequency; follow this condition: the longest sn-gram should consist of at most 8 words, with a total character count below 30. If a n-gram exceeds this limit, it can be broken into two or more n-grams and listed separately.
I need to find such n-grams for all of these text messages and sort them by their number of occurrences in descending order.
How to I approach this problem? I need a solution in javascript.
PS: I need help, but do not know to where to ask this. If the question
is not for this site, then where should I post it? please guide this
newbie here.
May be you can approach as follows. I will edit to add explanation as soon as i have some time.
var subSentences = (w,...ws) => ws.length ? ws.reduce((r,s) => (r.push(r[r.length-1] + ` ${s}`), r),[w])
.concat(subSentences(...ws))
: [w],
frequencyMap = sss => sss.reduce((map,ss) => subSentences(...ss.split(/\s+/)).reduce((m,s) => m.set(s, m.get(s) + 1 || 1), map), new Map());
frequencies = frequencyMap(["this is a test string",
"this is another one",
"yet another one is here"]);
console.log(...frequencies.entries()); // logging map object seems not possible hence entries
.as-console-wrapper { max-height : 100% !important
}
My textfield has this value:
"1
2 2
3
4 4
5 a
6
7
8
"
When I split it by "\n" I get:
["1", "2 2", "3", "4 4", "5 a", "6", "7", "8", ""]
I want to delete the last element. I'm doing this:
$('#textArrayId').val().replace($('#textArrayId').val().split("\n")[$('#textArrayId').val().split("\n").length - 1], "")
And I can't get it to delete. What to do?
I want to do this with string operations, not array operations.
To remove the last line, use this
var lines = $('#textArrayId').val().split("\n");
var withoutLastLine = lines.slice(0, -1).join("\n");
$('#textArrayId').val(withoutLastLine);
Or if you want to remove the last line without whitespace:
var lines = $.trim($('#textArrayId').val()).split("\n");
var withoutLastLine = lines.slice(0, -1).join("\n");
$('#textArrayId').val(withoutLastLine);
To remove the last element of an array, use this expression to receive all elements but the last:
x.slice(0, -1)
It would be better to trim off the whitespace before splitting. That way you can handle input more robustly:
var lines = document.getElementById('textArrayId').value
.replace(/^\s+|\s+$/g,'').split(/\s+/);
The regex used in the split will also allow for input like:
1 2
3 4 5 6
7 8
Also note: No jQuery used ^_^
you can use the bounded array like a[7] to store the value from 1 to 8 .