Comparison an array in java script [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have problem regarding how to compare string in an array..
in my list have jack,john,nami#domain,nami
function **alreadyInList**(list, toBeAdded) {
// return true or false
var delims = "(,)";
var tokens = list.split(delims);
for ( var i = 0; i < tokens.length; i++){
if (tokens[i] === toBeAdded ){
return true;
}
else
return false;
}
}
function addListTo(selectbox, textbox) {
var values = new Array();
var c = 0;
for ( i = 0; i < selectbox.options.length; i++) {
if (selectbox.options[i].selected) {
if (!**alreadyInList**(textbox.value,selectbox.options[i].value)) {
values[c++] = selectbox.options[i].value;
}
}
}
if (values.length == 0) return;
var v = values[0];
for (i = 1; i < values.length; i++) {
v += ',' + values[i];
}
if (textbox.value.length>0) {
if (textbox.value=='Any') {
textbox.value = v;
} else {
textbox.value += ',';
textbox.value += v;
}
} else {
textbox.value += v;
}
}
when i put my condition and i want to add the string into textbox it only work for the first string lets say i put nami as my string then when i want to put nami again it cannot so it works..but after "," i put name#domain .i can put back nami..means i dont want to repetitive string inside my textbox.can someone help me.sorry im still new in this programming..sorry for my english

Here is a revised version of your function to check if a name appears twice in any string in the array
function alreadyInList(list, toBeAdded) {
// return true or false
var delims = ",",
tokens = list.split(delims),
found = false;
var end = tokens.forEach(function (value) {
if (value.indexOf(toBeAdded) !== -1 && found == false) {
found = true;
alert('It\'s been found!');
// Do something
return true;
}
return false;
});
if (found != true) {
alert('Not in the list');
return false;
} else {
return false;
}
}
alreadyInList('marry,joe,gerry', 'marry');
JSFiddle Demo
Additionally if its just one occurance in the list you need something simple without a function.
var str = "marry,joe,gerry",
key = "marry";
if ( str.indexOf(key) !== -1 ) {
// Its found! Do something
}

As Sasquatch pointed out above, the issue is the delimiter you are using for split. You want to split by a single comma ',' -- not by the three characters '(,)'.
The way your code is written, tokens only ever has a single value because the split delimiter is wrong. It is matching the entire string variable list to your toBeAdded string and returning false.

Related

How do I join these arrays is one? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
calculaNumeroDaSenha(['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']);
function calculaNumeroDaSenha(senha) {
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
function filtro1(modo1) {
return modo1 == "1"
}
function filtro2(modo2) {
return modo2 == "0"
}
etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
function etapaFinal(x,y) {
var novaArray = [];
if (x.length > y.length || x.length == y.length) {
novaArray.push('1')}
else {
novaArray.push('0');
}
console.log(novaArray);
};
}
}
the code output looks like this:
['0']
['1']
['1']
['1']
['1']
['1']
['1']
['1']
['1']
['0']
But I want the output to come out in just an array, like this:
['0111111110']
I've already tried methods like the join() function, but it didn't work:
function etapaFinal(x,y) {
var novaArray = [];
if (x.length > y.length || x.length == y.length) {
novaArray.push('1')}
else {
novaArray.push('0');
}
for (let a = 0; a < novaArray.length; a++) {
console.log(novaArray[i].join());
}
};
Please, if you have any idea how to do this, no matter how, help me if possible.
So it seems like your fundamental misunderstanding is how .push works. Push, as the name implies, pushes a new value to the end of the array. Thus instead of pushing to an array, what you need to do is just build up a string and then push that string at the end.
Looks like your code will either return a 1 or a 0 depending on what filter. Thus your new code can look like so:
function calculaNumeroDaSenha(senha) {
let result = '';
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
const filtro1 = (modo1) => {
return modo1 == "1"
}
const filtro2 = (modo2) => {
return modo2 == "0"
}
const etapaFinal = (x,y) => {
if (x.length > y.length || x.length == y.length) {
return '1';
}
else {
return '0';
}
};
result += etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
}
return [result];
}
Where if we then log it out as so: console.log(calculaNumeroDaSenha(['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']));
we get an array of size 1 of the following results: ['0111111110']. JSFiddle: https://jsfiddle.net/avnkj81z/
One thing I did, is I changed your inner function blocks to be defined instead using the following pattern: const <functionName> = <(parameters)> => {...}. This is because it makes it easier to read and you don't have one function nested in one after the other. Note that function A(b) { returns b; } is equivalent to const A = (b) => { returns b;}
To join all the strings into one string, use Array.join().
The question is kinda vague, you need to clarify what you're looking for:
if you are looking to group an array items into one string, you would use Array.join().
const arr = ['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']
arr.join('');
// the above command would result in a single string with all array values concatenated
// "0110100000100101111111100010100111010101001110011010100110011101100100101101010010011001111000011000"
However if you're looking to group all array elements into one array that has a single string with all array elements grouped, you would use Array.join() followed by String.split()
const arr = ['0110100000', '1001011111','1110001010', '0111010101','0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']
arr.join('').split();
// the above command would result in a single array with one string with all array elements grouped
// [ "0110100000100101111111100010100111010101001110011010100110011101100100101101010010011001111000011000" ]
I think you want the output of this code. Please look into it. It is printing your desired value.
calculaNumeroDaSenha(['0110100000', '1001011111', '1110001010', '0111010101', '0011100110', '1010011001', '1101100100', '1011010100', '1001100111', '1000011000']);
function calculaNumeroDaSenha(senha) {
var novaArray = [];
var str = '';
for (let i = 0; i < senha.length; i++) {
var dividir = senha[i].split('');
function filtro1(modo1) {
return modo1 == "1"
}
function filtro2(modo2) {
return modo2 == "0"
}
etapaFinal(dividir.filter(filtro1), dividir.filter(filtro2));
function etapaFinal(x, y) {
if (x.length > y.length || x.length == y.length) {
str += 1;
}
else {
str += 0;
}
};
}
novaArray.push(str);
console.log(novaArray);
}

Parsing JSON from string containing JSON object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a string like
"Something has happened {\"prop1\":{\"name\":\"foo\"}}"
and I would like to parse out the JSON so that I can format the string. Such as:
Something has happened
{
"prop1":{
"name":"foo"
}
}
In JavaScript, what would be a good way to accomplish this.
There can be multiple object in the string and also the object will not be known it could contain many nested objects or arrays. Thanks in advance.
The minimum would be simply pretty-printing the string
OK then. Well a really simple, non-optimised, not-necessarily robust pretty print function might look something like this:
function basicPrettyPrint(str) {
var output = '';
var indentLevel = 0;
var indent = ' ';
var inQuotes = false;
for (var i = 0; i < str.length; i++) {
var current = str[i];
if (current === '"' && indentLevel > 0) {
inQuotes = !inQuotes;
output += current;
} else if (inQuotes) {
output += current;
} else if (current === ',' && indentLevel > 0) {
output += ',\n' + indent.repeat(indentLevel);
} else if (current === '{' || current === '[') {
if (indentLevel === 0) output += '\n';
output += current + '\n' + indent.repeat(++indentLevel);
} else if (current === '}' || current === ']') {
output += '\n' + indent.repeat(--indentLevel) + current;
if (indentLevel === 0) output += '\n';
} else {
output += current;
}
if (indentLevel < 0) {
// parse failure: unbalanced brackets. Do something.
}
}
return output;
}
var input = 'Here is a "simple" object, for testing: {"prop1":{"name":"foo"}}And here is a more complicated one that has curly brackets within one of the property values:{"prop1":"{this is data, not an object}","arr":[1,{"a":"1","b":{"x":1,"y":[3,2,1]}},3,4]}And a non-nested array:[1,2,3]';
console.log(basicPrettyPrint(input));
The above doesn't allow for escaped quotation marks within properties, and probably a bunch of other things I didn't think of for purposes of a quick demo, but I leave those things as exercises for the reader...
P.S. The string .repeat() method might need to be polyfilled.
Can we assume that the '{' and '}' indicate the start and end of the json. If so, you can get a substring; see code below. You could do the same thing with regular expressions.
var str = "Something has happened {\"prop1\":{\"name\":\"foo\"}}"
var start = str.indexOf("{");
var end = str.lastIndexOf("}");
var json = str.substr(start, end);

Split a variable using mathematical equations in javascript

I have two questions actually.
What I want to do is 1st to check if the user entered value is a correct mathematical equation. For example, if the use enters x + y ( z this should detect as an invalid formula and x + y ( z ) as a correct one,
The 2nd thing I want to do is to split the formula from the + - * / () signs, so the above formula will be return as x, y, z.
What I have done is bellow
var arr = [];
var s = 'x + y ( z )';
arr = s.split("(?<=[-+*/])|(?=[-+*/])");
console.log(arr);
This returns a single array with just one data like, [x + y ( z )]
Another thing, the variables are not single letters. they could be
words like, annual price, closing price, etc
Can someone help me in this problem. Thanks in advance
UPDATE : I have tried "/[^+/*()-]+/g" also
For the second part:
var s = 'x + y ( z )';
var arr = s.match(/(\w)/g);
console.log(arr);
document.write(JSON.stringify(arr));
Of course, you have to check the validity of the input first.
Edit: using Tomer W's answer suggesting eval():
function checkExpression(str) {
// check for allowed characters only
if (/[^\w\d\(\)\+\*\/\-\s]/.exec(s) != null)
return false;
// extract variable names, assuming they're all one letter only
var arr = s.match(/(\w+)/g);
// instantiate the variables
arr.forEach(function (variable) {
eval(variable + '= 1');
});
// ( is alone, replace it by * (
str = str.replace(/\(/g, '* (');
try {
eval(str);
return true;
}
catch (ex) {
console.log(ex);
return false;
}
}
It's dirty but it works most of the time (Tomer W pointed some edge cases like ++62+5 or 54++++6 that can be avoided with an another regex check), do you have more complicated example to test?
Word of warning
VERY VERY VERY DANGEROUS METHOD AHEAD !!!
I am posting this as it is a valid answer, but you should do it only with extreme caution as a user can totally mess up your site.
DO not let the one user input be used in eval for another user !!! EVER !!!
Actual answer
You can use the built-in java-script compiler of your browser, and use eval()
function checkEq(equ)
{
for(ch in equ){
// check that all characters in input are "equasion usable"
if(" +-*/1234567890e^&%!=".indexOf(ch) === -1)
{ // if there are invalid chars
return false;
}
}
try{
// try running the equ, will throw an exception on a syntax error.
eval(equ);
return true; // no exception
}
catch(ex){
return false; // syntax error
}
}
Plunker example
and as i noted before! extreme caution!
Using both #ShanShan and #Tomer W answers, I wrote a formula validator. the code is bellow. In this validator, I checks for opening and closing brackets, extra / * - + signs, unwanted symbols, etc.
If the user wants to create and validate a formula with x,y,z
variables, user have to add the variables to an array and pass it to
this validator with the formula written so the validator accepts the
variables which are not numbers.
I also used a custom set mentioned in this post. https://stackoverflow.com/a/4344227/918277
Important : This java script function can't validate very complex formulas with sin, cos, tan, log, etc. Script will identify them as just letters and will return false.
function StringSet() {
var setObj = {}, val = {};
this.add = function(str) {
setObj[str] = val;
};
this.contains = function(str) {
return setObj[str] === val;
};
this.remove = function(str) {
delete setObj[str];
};
this.values = function() {
var values = [];
for ( var i in setObj) {
if (setObj[i] === val) {
values.push(i);
}
}
return values;
};
}
/**
*
* #param _formulaInputs
* Array of use entered inputs to be use in formula
* #param _formula
* User entered formula
* #returns {Boolean}
*/
function validateFormula(_formulaInputs, _formula) {
var formula = _formula;
var bracketStack = new Array();
var formulaDescArray = [];
var formulaDescInForm = new StringSet();
for (var i = 0; i < _formulaInputs.length; i++) {
formulaDescInForm.add(_formulaInputs[i]);
}
/* Regex to check for unwanted symbols(! # # $ etc.) */
if (/[^\w\d\(\)\+\*\/\-\s]/.exec(formula) != null) {
return false;
}
for (var i = 0; i < _formula.length; i++) {
if ((_formula.charAt(i) == '/' || _formula.charAt(i) == '*'
|| _formula.charAt(i) == '-' || _formula.charAt(i) == '+')
&& (_formula.charAt(i + 1) == '/'
|| _formula.charAt(i + 1) == '*'
|| _formula.charAt(i + 1) == '-' || _formula
.charAt(i + 1) == '+')) {
return false;
}
}
var lastChar = formula.charAt(formula.length - 1);
if (lastChar == '/' || lastChar == '*' || lastChar == '-'
|| lastChar == '+') {
return false;
}
formulaDescArray = formula.split(/[\/\*\-\+\()]/g);
/* Remove unwanted "" */
for (var i = 0; i < formulaDescArray.length; i++) {
if (formulaDescArray[i].trim().length == 0) {
formulaDescArray.splice(i, 1);
i--;
}
}
/* Remove unwanted numbers */
for (var i = 0; i < formulaDescArray.length; i++) {
if (!isNaN(formulaDescArray[i])) {
formulaDescArray.splice(i, 1);
i--;
}
}
for (var i = 0; i < formulaDescArray.length; i++) {
if (!formulaDescInForm.contains(formulaDescArray[i].trim())) {
return false;
}
}
for (var i = 0; i < formula.length; i++) {
if (formula.charAt(i) == '(') {
bracketStack.push(formula.charAt(i));
} else if (formula.charAt(i) == ')') {
bracketStack.pop();
}
}
if (bracketStack.length != 0) {
return false;
}
return true;
}

How to sort variable data in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am creating one function in javaScript:
function myFunction() {
var str = "1,12,3,4";
if (str.contains("1,12,4,3")) {
alert("yes");
} else {
alert("No");
}
}
o/p: NO..i want the o/p as "Yes " because all elements are there.
I think you want to compare the comma separated elements contained in the string, not the string itself.
So you can use split and sort to build and sort your arrays and an "equality function" to check them.
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can try use a sorting/comaring function:
var str = "1,12,3,4";
var str2 = "1,12,4,3";
var myArray1 = str.split(",");
var myArray2 = str2.split(",");
alert(arraysEqual(myArray1, myArray2))
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
a.sort();
b.sort();
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
Demo: http://jsfiddle.net/IrvinDominin/ZT4M8/
String "1,12,3,4" really doesn't contain substring "1,12,4,3". You're shuffling arrays and strings methods. You should convert your string to array (e.g. using split() method), then possible order and after all match.
try this
function myFunction() {
var str = "1,12,3,4";
var str_to_match = "1,12,4,3";
var res = str.split(",");
var res_to_match = str_to_match.split(",");
var flag=1;
for(var i=0; i<res_to_match.length; i++)
{
if(!res.contains(res_to_match[i]))
{
flag=0;
break;
}
}
if (flag==1) {
alert("yes");
} else {
alert("No");
}
}
I think, what you are looking for are the functions split, join and sort:
var myArray = str.split(","); // creates an array with your numbers
myArray.sort(); // sorts the array
var sortedStr = myArray.join(","); // creates a comma separated string of the sorted array

Javascript in list

What's the easiest way to check to see if a number is in a comma delimited list?
console.log(provider[cardType]);
//returns: Object { name="visa", validLength="16,13", prefixRegExp=}
if (ccLength == 0 || (cardType > 0 && ccLength < provider[cardType].validLength)) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}
Seems similar to this SO question.
Just .split() the CSV and use inArray.
Not sure how your sample code relates to checking to see if a number is in a comma delimited list...
Also not sure if this is the easiest way, but it's what springs to mind:
<script type="text/javascript">
var myNumbers = "1,2,3,4,5";
var myArray = myNumbers.split( ',' );
// looking for "4"
for ( var i=0; i<myArray.length; i++ ) {
if (myArray[i] == 4) {
alert('Found it!');
break;
}
}
I do not see where you have a significant comma delimited list in the script you posted.
The fastest way could be something like
var csvList ="a,b,c,d,e,f,g,h";
var testList = ","+csvList+",";
var needle = "f";
alert(testList.indexOf(","+needle+",")!=-1)
just to be different ;)
If it's just a list of comma separated numbers with nothing fancy, you can just use the split method:
var numbers = list.split(",");
This will give you an array of all of the numbers in the list. Checking whether a number is in an array is trivial.
Native JavaScript and therefore cross-browser compliant. Some frameworks provide functions that do this for you, but you don't get more basic than the following.
var numbers = list.split(",");
var count = numbers.length;
var exists = false;
for (var i = 0; i < count; ++i) {
if (numbers[i] == anumber) {
exists = true;
break;
}
}
From your sample, I assume your question was "How do I see if a number is within a range of two values specified by a single-comma-delimited string?":
function inRange( number, stringRange ){
var minmax = stringRange.split(',');
minmax[0] = minmax[0]*1; //convert to number
minmax[1] = minmax[1]*1; //convert to number
minmax.sort(); // Ensure [0] is the min
return number>=minmax[0] && number<=minmax[1];
}
Try this one...
console.log(provider[cardType]); //returns: Object { name="visa", validLength="16,13", prefixRegExp=}
var regExp = new RegExp(",?" + ccLength + ",?");
if (ccLength == 0 || (cardType > 0 && !regExp.test(provider[cardType].validLength)))
{
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
}
else
{
if ($('.credit-card input[name="cc_cvv"]').val().length < 3)
{
triggerNotification('x', 'You must provide a CCV');
return false;
}
}

Categories