Getting range from a list using regular expressions - javascript

I have a list of numbers such as
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
This list can have negative, positive numbers with optional decimal values, also negative or positive.
I need to use regular expressions to do 3 things:
getAllNumbersBeforeValue(value);
getAllNumbersAfterValue(value);
getRangeBetweenValues(valueFrom, valueTo);
Value passed in is not known, could be any number.
Update 1:
I've got this, which isn't perfect but works on some numbers:
var a = function(rand) {
var val = "";
var numArr = rand.split("");
for(var i = 0; i < numArr.length; i++) {
val = val + (Number(numArr[i])+1);
}
return "^[^" + val.split("").join("-9][^") + "-9]$"
}; // outputs "^[^2-9][^3-9][^4-9][^5-9][^6-9]$" with rand "12345"
Im trying to get a regular expression programmatically generated from a given value
For example "123456" is a random number (rand), I would like to be able to filter an array of numbers for values that are higher then rand (or lower then rand) using a regex value.
Thanks

You could use underscore.js (http://underscorejs.org) to filter your results. For example...
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
function getAllNumbersBeforeValue(list, value) {
return _.filter(list, function(num) {
return num < value;
});
}
Here's an example without using a framework...
function getAllNumbersBeforeValue(list, value) {
var output = [];
for(var i = 0; i < list.length; i++) {
if(list[i] < value) {
output.push(list[i]);
}
}
return output;
}
getAllNumbersBeforeValue(list, 123);

Related

How to add sum of currency values of an array in javascript

how to add currency values of an array like this
array = [ '$0',
'$0',
'$14,792',
'$152,445',
'$1,581,033',
'$2,988,978',
'$4,226,419',
'$7,254,960',
'$10,726,945',
'$12,657,402',
'$35,215,787',
'$37,968,368',
'$7,648,445',
'$364,237',
'$390,395',
'$306,080',
'$3,641,253',
'$4,328,363',
'$1,360,664' ]
here is my method defined, the only problem i am facing is in the second for array_sum is not adding the values that i am getting from data variable.
exports.GetMonthsFWSeasonFullSeasonValues = () => {
var promises = [];
var array_sum = 0;
for(var month_index = 9; month_index <= 27 ; month_index++){
const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
promises.push(element(by.xpath(elm_xpath)).getText());
}
return Promise.all(promises).then(function(data){
if(data != null) {
for (var array_index = 0; array_index < data.length; array_index++){
array_sum += data[array_index];
console.log('sum of values from months',array_sum);
}
} else {
return null;
}
});
};
The problem here is that you are trying to add two strings. The + operator is overloaded in JS, so with numbers it adds them, but with strings it concatenates them. You need to convert them to ints or floats by using parseInt or parseFloat, and get rid of the commas and $ signs out of it, something like:
var num = '$1,100'
parseInt(num.replace(/[$,]/g, ''))
Which would give 1100 if you printed it. After they are in number format, you can sum them.
Or if you have the choice to store the numbers in your array as numbers, without the string formatting to start off with, go with that. So much easier.

jQuery - Round Up all Currency Prices with Multiple Elements

I'm working in Shopify with it's currency switcher and the problem is, the client I'm working with wants every currency bar the default (GBP) to round it's price up to the nearest whole number, so $458.54 becomes $459.
I almost got it to work, except when more than one .money element is present, it seems to break and merges them together.
The JS code is:
var all = $(".money")
.map(function() {
return this.innerHTML;
})
.get();
var all = [all, ","];
var arrayLength = all.length;
for (var i = 0; i < arrayLength; i++) {
//Do something
}
console.log("array:", all);
var regex = all.toString().replace(/[^0-9.]/g, "");
var regex = [regex, ","];
var regexarrayLength = regex.length;
for (var i = 0; i < regexarrayLength; i++) {
//Do something
}
console.log("arrayregex:", regex);
console.log("regex:", regex);
var rounded_currency = Math.round(regex);
console.log("rounded_currency:", rounded_currency);
$("#update").click(function() {
alert(rounded_currency);
});
$(document).ready(function() {
$(".priceUpdate").text(regex);
$(".priceRound").text(rounded_currency);
});
CodePen Example
You can make use of javascript's Math.ceil() function to round up to the nearest integer.
For example, loop over the array of all selectors with the .money class and first strip the dollar sign. Then call Math.ceil().
var all = $(".money").map(function() {
return this.innerHTML;
}).get();
//["$6453.65", "$6453.65", "$453.65", "$643.65", "$6564453.65"]
var rounded = all.map(function(x) {
var numbers = x.replace(/[^0-9]/, '');
return Math.ceil(numbers);
});
//[6454, 6454, 454, 644, 6564454]
To achieve expected result, use below option
Changing array of prices to rounded prices array,as regex is not a proper array that is why it is throwing NaN
Updated codepen with JPY value for testing
console.log("array:", all);
var prices = all[0].map(function(num){
return var prices = all[0].map(function(num){
return Math.round(num.replace(/,/g, '').substr(1));
})
console.log(prices)
})
console.log(prices);//rounded prices [6454,6454,454,644,6564454]
Codepen-https://codepen.io/nagasai/pen/VbMZBz?editors=1111

Counting the frequency of elements in an array in JavaScript

how do I count the frequency of the elements in the array, I'm new to Javascript and completely lost, I have looked at other answers here but can't get them to work for me. Any help is much appreciated.
function getText() {
var userText;
userText = document.InputForm.MyTextBox.value; //get text as string
alphaOnly(userText);
}
function alphaOnly(userText) {
var nuText = userText;
//result = nuText.split("");
var alphaCheck = /[a-zA-Z]/g; //using RegExp create variable to have only alphabetic characters
var alphaResult = nuText.match(alphaCheck); //get object with only alphabetic matches from original string
alphaResult.sort();
var result = freqLet(alphaResult);
document.write(countlist);
}
function freqLet(alphaResult) {
count = 0;
countlist = {
alphaResult: count
};
for (i = 0; i < alphaResult.length; i++) {
if (alphaResult[i] in alphaResult)
count[i] ++;
}
return countlist;
}
To count frequencies you should use an object which properties correspond to the letters occurring in your input string.
Also before incrementing the value of the property you should previously check whether this property exists or not.
function freqLet (alphaResult) {
var count = {};
countlist = {alphaResult:count};
for (i = 0; i < alphaResult.length; i++) {
var character = alphaResult.charAt(i);
if (count[character]) {
count[character]++;
} else {
count[character] = 1;
}
}
return countlist;
}
If you can use a third party library, underscore.js provides a function "countBy" that does pretty much exactly what you want.
_.countBy(userText, function(character) {
return character;
});
This should return an associative array of characters in the collection mapped to a count.
Then you could filter the keys of that object to the limited character set you need, again, using underscore or whatever method you like.
Do as below:
var __arr = [6,7,1,2,3,3,4,5,5,5]
function __freq(__arr){
var a = [], b = [], prev
__arr.sort((a,b)=>{return a- b} )
for(let i = 0; i<__arr.length; i++){
if(__arr[i] !== prev){
a.push(__arr[i])
b.push(1)
}else{
b[b.length - 1]++
}
prev = __arr[i]
}
return [a , b]
}

How can I avoid counting triplicates as pairs while iterating through an ordered series of letters within an array?

I wrote a simple program to analyze a string to find the word with the greatest amount of duplicate letters within it. It essentially takes a given string, breaks it up into an array of separated words, and then breaks up each separate word into alphabetically sorted groups of individual letters (which are then compared as prev and next, 2 at a time, as the containing array is iterated through). Any two adjacent and matching values found adds one tally to the hash-file next to the word in question, and the word with the most tallied pairs of duplicate letters is returned at the end as greatest. No matching pairs found in any word returns -1. This is what it's supposed to do.
Below, I've run into a problem: If I don't use a REGEXP to replace one of my matched characters, then my code gives false positives as it will count triplicates (eg, "EEE"), as two separate pairs, (eg, "EEE" = "EE & EE", instead of being viewed as "EE, E"). However, if I DO use the REGEXP below to prevent triplicate counts, then doing so breaks my loop mid-stride, and skips to the next word. Is there no way to make this way work? If not, would it be better to employ a REGEXP which deletes all chars EXCEPT the duplicate characters in question, and then perhaps I could divide the .length of each word by 2 to get the number of pairs remaining? Any ideas as to how to solve this would greatly help.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str) {
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++) {
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++) {
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j]) {
counter++;
hashObject[final] = counter;
//currentWordIntoChars = currentWordIntoChars[j-1].replace(/[a-z]/gi, String.fromCharCode(currentItem.charCodeAt(0)+1));
//HERE REPLACE j-1 with random# or something
//to avoid 3 in a row being counted as 2 pair
//OR use regexp to remove all but pairs, and
//then divide .length/2 to get pairs.
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem]) {
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));
An other way to do it, consists to replace duplicate characters in a sorted word:
var str = "Helloo aplpplpp pie";
function LetterCountI(str) {
var input = str.split(" ");
var count = 0;
var result = -1;
for(var i = 0; i<input.length; i++) {
var nb = 0;
var sortedItem = input[i].split("").sort().join("");
sortedItem.replace(/(.)\1/g, function (_) { nb++ });
if (nb > count) {
count = nb;
result = input[i];
}
}
return result;
}
console.log(LetterCountI(str));
Notes: The replace method is only a way to increment nb using a callback function. You can do the same using the match method and counting results.
if two words have the same number of duplicates, the first word will be returned by default. You can easily change this behaviour with the condition of the if statement.
Whenever you find a match within a word, increment j by 1 to skip comparing the next letter.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str)
{
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++)
{
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++)
{
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j])
{
counter++;
hashObject[final] = counter;
j++; // ADD HERE
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem])
{
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.
My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.
function TallyPoints() {
var eles = [];
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
total += document.getElementsByName(inputs[i].name)[0].value;
}
}
alert('Total: ' + total.toString());
};
What I end up with is a value that looks like this:
Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}
Any ideas?
You probably want parseFloat() so your addition works properly (fiddle):
var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
return p + (parseFloat(c.value) || 0);
}, 0);
See also parseInt(), isNaN(), and Array.prototype.reduce()
Try this:
function TallyPoints() {
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.indexOf('txtpoints') == 0) {
var val = parseFloat(inputs[i].value);
if (!isNaN(val)) {
total += val;
}
}
}
alert('Total: ' + total);
};
parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName, since you already have the element in inputs[i]. There's no need to use total.toString(); concatenating a number to a string converts it automatically.
The if (!isNan(val)) test skips over the inputs that don't contain numbers.
You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

Categories

Resources