Check Duplicate Value in array javascript - javascript

I need to check to 1 array value, if value duplicated, it will pop up alert.
Here is the function :
function checkDuplicateTenure(){
var f = document.frmPL0002;
var supplgrid = document.getElementById("mdrPymtGrid2");
var len = (supplgrid.rows.length) - 1;
for(var i=0;i<len;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
return false;
}
That function is works if got duplicate value in array, but if all value is different, its will hit js error if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) { Unable to get property 'value' of undefined or null reference.
Thanks

This is a simple out of bounds error. Fix it by using this:
for (var i=0;i<len-1;i++) {
So, i+1 will never be the same as len.

change it
for(var i=0;i<len-1;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
suppose your loop runs 5 times and you can set i+1 inside the loop it comes 6 which is undefined index that why js error occurs

Try this:
function checkDuplicateTenure(){
var f = document.frmPL0002;
var supplgrid = document.getElementById("mdrPymtGrid2");
var len = (supplgrid.rows.length) - 1;
for(var i=0;i<len-1;i++){
if (f.cbo_loanTenure[i+1].value == f.cbo_loanTenure[i].value) {
alert("DUPLICATE LOAN TENURE IN MONTH(S)");
}
}
return false;
}

Related

Sort function that uses an integer array argument doesnt work

I'm a beginner trying to learn JS, I've got some basic knowledge.
I wrote a function to realize insertion sort on a given array (the array is passed on to the function as a parameter).
When I initialize the array and give it value, e.g,
sampleArray = [1,35,73,234,1,1,356];
and pass that to my function, it works perfectly.
however, if I try to pass on an array filled by user input - or an array that was merged out of two given arrays (my original assignment),
it doesn't work - no exceptions or errors, it just... doesn't sort as expected.
I've been racking my mind over this, maybe I don't know where to look?
function sortArray(arrT) {
for (let i = 1; i < arrT.length; i++){
var tempMax = arrT[i];
var j = i - 1;
while ((j >= 0) && (arrT[j] > tempMax)) {
console.log(arr1 + "\nj=" + j + " i=" + i);
arrT[j+1] = arrT[j];
j--;
}
arrT[j+1] = tempMax;
}
console.log("sorted array is (inside loop) :\n" +arrT);
return arrT;
}
for an array that was filled by a while loop of prompts such as
it's equal to the above sample array, the result is
1,1,1,234,35,356,73
for reference, though it's far from elegant, I'm using this to fill the array:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
As per my understanding.
The mistake is here
Original Code:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");//do not use prompts while unnecessary. Just replace it with x;
}
Corrected One:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
/*
you can also improve your code by applying few checks
if(!isNaN(x)) continue; // --- to skip when input value isn't a number
*/
arr1[i]=x;
}
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
prompt actually returns a string, hence your input is an array of strings instead. You should use Number to ensure the provided value is numeric.
I would rewrite the above in this way:
// stores all the values.
var arr1 = [];
// Stores the current value.
var input;
do {
var _ = prompt("press x to finish, enter to continue"); // <-- not sure why you're doing that every time, I would suggest you to move it outside of the loop.
input = prompt("enter");
var n = Number(input);
if (!isNaN(n)) arr1.push(n); // <-- checks whether the provided value is actually numeric and a valid number. If it is, the value is added to the collection.
}
while (input !== 'x');
console.log(arr1);
I would suggest you to move the first prompt outside of the loop, but since you did it in your code, I suspect there is a reason for that, though I don't get it.
In any case, the above sample will check whether the value passed is valid; if it is, it push the item to the collection, otherwise it continues until 'x' is met.

if condition in javascript function not working

I need to compare the values and return the message.But the message returned always. How can i do it?
Javascript:
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
for (var i = 0; i < grid.rows.length - 1; i++) {
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]")
var cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (txtcurrentrcvamount > cell) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}
You need to take the value of your input:
var txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val()
// ^^^^^^
Since you're comparing numbers, and val() and text() return strings, you should convert your values to numbers before doing the comparison:
if (Number(txtcurrentrcvamount) > Number(cell))
Do note that Number(someStringThatIsNotANumber) will return NaN
Because your scope of a variable (txtcurrentrcvamount) is limited in between for loop, That's why this not working outside the loop scope.
for more detail, you can view this post...scope of variables
For using this variable in if condition you have initialized it before the for loop...
EDIT:
Try this may this help you either. I think there some other finding to suppose you have two rows in your grid then which row value you want to check because this always return last row value... and if there a number value for both of the variable assignment txtcurrentrcvamount ,cell then it should be work perfectly.
function Calculation() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
var txtcurrentrcvamount ;
var cell;
for (var i = 0; i < grid.rows.length - 1; i++) {
txtcurrentrcvamount = $("input[id*=txtrcvQuantity]").val();
cell = $("#gvGoodReceived").find("tr:eq(0)").find("td:eq(2)").text();
}
if (Number(txtcurrentrcvamount) > Number(cell)) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
return true;
}

Get max or min value from associative array with function and parameters

Here is the code as far as I got it right now:
<!DOCTYPE html>
<html>
<body>
<button onclick="scanarray('a', 'max')">Test with a, max</button>
<button onclick="scanarray('b', 'min')">Test with b, min</button>
<p id="demo">test</p>
<script>
var array = [{"a":1},{"b":3},{"a":6},{"b":10}];
var max = null;
var min = null;
var value = null;
function scanarray(scanval, searchterm) {
if (array.length < 1) {
return -1;
}
if(searchterm == "max"){
max = Math.max.apply(Math,array.map(function(e){return e.scanvalue;}))
}else if (searchterm == "min"){
min = Math.min.apply(Math,array.map(function(e){return e.scanval;}))
}else
{document.getElementById("demo").innerHTML = "Only max and min available";}
if(searchterm == "max"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + max;
}
if(searchterm == "min"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + min;
}
}
</script>
</body>
</html>
The above should give me a and 6 or b and 3 as results. However I get NaN as result for the value part. When using "return e.a" in the Math section and only having a as keys it works.
I want to be able to determin the max or min value of a key I enter as parameter to the function.
Hope you can help me here.
Thanks in advance.
TheVagabond
There are some naming mess in your code. For example scanvalue is name of your function but you are trying to reach it as a parameter of e(e.scanvalue). I should be scanval. But still there are some problems. You can't reach property "a" or "b" of e if e.scanval. You're trying to reach variable of variable.
Then, you should use e[scanval]. It returns you to value of "a" or "b". But if object doesn't have one of them? Then you should add "|| 0" to get correct value. (Instead of NaN or undefined) It means that; use e[scanval] if its valid, if not use 0.
Use this;
return e[scanval] || 0;
If your boundaries include some negative values, use something like -9999 or -Infinity.
You are getting Nan because e.scanvalue returns undefined in your case.
Try using custom function.
function getValue(arr){
var res = [];
for(var j = 0; j < arr.length; j++)
{
for(var anItem in arr[j])
{
res.push(arr[j][anItem]);
}
}
return res;
}
and call this function like
max = Math.max.apply(Math,getValue(array))
and
min = Math.min.apply(Math,getValue(array))
accordingly.
Hope this helps!!!!

iterate two arrays and perform AND / OR comparison = return true

Here is my current filter function (quite incomplete)
$('input:checkbox.types').click(function(){
filterMarkers();
});
function filterMarkers() {
var checked = [];
$('input:checkbox.types:checked').each(function(){
checked.push($(this).val());
});
checked.sort();
var andor = '';
var andor = $('[name="and-or"]:checked').val();
if(andor == 1) {
// and
console.log(checked);
for (var i = 0; i < markers.length; i++) {
var types = markers[i]['types'].split(",");
types.sort();
console.log(types);
}
} else {
// or
}
}
Here is an image of what I have so far.
http://snag.gy/rKSTA.jpg
Let us say this for simplicity.
A = checked checkboxes
B = array with values of current item in map marker iteration / current iteration marker
I was able to get the values of the checked checkboxes. I was also able to convert the comma delimited string of each marker into an array. I would like to be able to check if B contains ANY of A (OR) and be able to check that B must contain A (AND).
Any ideas?
Here is the page in question for those wanting a 'feel' for what I am trying to accomplish. Thanks!
https://www.cablework.co/company
This page outputs what I have currently to console.
Once I can figure this out, I will then be able to hide/show markers based on the result.
Here's an example function. You would run test on every marker against the types array.
http://jsfiddle.net/q1k6e74d/5/
function test(op,types,marker){
var pass;
if(types.length === 0 || marker.length === 0){
return false;
}
if(op==="and"){
pass = true;
for(var i in types){
if( $.inArray(types[i],marker) == -1 ){
pass = false;
}
}
}else{ //or
pass = false;
for(var i in marker){
if( $.inArray(marker[i],types) !== -1 ){
pass = true;
}
}
}
return pass;
}
var a = [1,4];
var b = [1,5];
console.log("test a",a,"and b",b,test("and",a,b));
console.log("test a",a,"or b",b,test("or",a,b));
Could be shorter but it's easiest to understand this way I think.

Form validation with Javascript and "undefined" problem

I build form validation with the code below. It`s work but If some of required field is filled var msg contains undefinied value.
For example if username is filled but password not var msg contains
'undefinied'
Field is requred
How to avoid that ?
Here is the code:
var i = 0;
var error_msg = [];
var msg = ;
var errors = {
'username' : 'Field is required',
'password' : 'Field is requred',
'city' : 'City is required'
etc...... etc...
};
for(var x in errors) {
i++;
if(!$('#'+x).val()) {
error_msg[i] = errors[x];
}
}
if(error_msg.length > 0) {
for(var x = 0; x < errors_msg.length; x++) {
msg += errors_msg[x] +"\n";
}
}
One thing I see is:
var msg = ;
Should(could) be
var msg = "";
Did you also try to:
alert($('#'+x).length);
To see if jQuery finds the element? (if it returns 0, then its not found)
OK, besides the obviously broken for in loop and the missing assignment of msg.
This is your actual problem:
var error_msg = []; // new empty array
for(var x in errors) {
i++; // i starts with 1 this way!
// other code
}
So you're never setting the 0th index. Yes arrays start with index 0. So if you set an index that's bigger then the current length of the array, JavaScript will insert the missing elements before that index.
In your case, JavaScript will insert the default undefined at index 0 since the first index you set is 1.
Fixing
var error_msg = [];
for(var x in errors) {
if (errors.hasOwnProperty(x)) { // see note below
if(!$('#'+x).val()) {
error_msg.push(errors[x]); // append to the array
}
}
}
var msg = error_msg.join('\n'); // no need for an if, will be empty if there are no errors.
Note: See hasOwnProperty
This is not your problem, and so this is not really an answer, but comments don't support code very well:
if(error_msg.length > 0) {
for(var x = 0; x < errors_msg.length; x++) {
msg += errors_msg[x] +"\n";
}
}
For future reference, you never need to write that code:
msg = errors_msg.join('\n');
does the same thing.

Categories