Simple javascript in_array recursive function - javascript

So for PHP I have a handy set of function for doing an in_array on multi dim arrays:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
However I have tried to recreate one similar in javascript but I cannot seem to get it to work.. this is what i have:
function in_array_r(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle){
return true;
}
if(typeof haystack[i]=='object'){
if(in_array_r(needle, haystack[i])){
return true;
}
}
}
return false;
}
Can anybody spot why it isn't working as I cannot see why it doesn't..
Thanks,
John

This works.. numeric and non-numeric keys.. doh!
function in_array_r(needle, haystack) {
var length = haystack.length;
for(var key in haystack) {
if(haystack[key] == needle){
return true;
}
if(typeof haystack[key]=='object'){
if(in_array_r(needle, haystack[key])){
return true;
}
}
}
return false;
}

Related

JavaScript condition not being met

I have created the below code for a subscribe form and for the most part it is working fine apart from, however the following condition does not seem to be working:
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
What is happening is that when the subValidEmail is entered correctly it clears all of the other entered data which leads me to believe that the subFieldUpdated === true condition is not being picked up correctly?
What I am looking for is that the form will only clear the values once all fields have been entered & a valid email is present.
Any suggestions/advice would be great as I have tried a few things now but with no luck.
$("#modSubCard").submit(function() {
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = true;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated[i] = false;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});
Use Below Code. It will works for you.
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = 0;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated = subFieldUpdated + 1;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === 0 && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});

Javascript in_array

In php this is a nice way of asking is a value is one of a few options
if( in_array($needle, [1,325,'something else']) ){
//do your thing
}
But in the world of javascript is there an equiv. that doesn't require writing a bespoke function such as:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
Use case of the above js bespoke function
if( inArray( somvar, [1,2,'something else']) ){
do the javascript thing
}
FROM THE COMMENTS
this is the most accurate answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var needle = 325;
if( [1,325,'something else'].indexOf(needle) !== -1 ){
//do your thing
};
You can use Array.prototype.find():
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

Faster Evaluating IF Condition of JavaScript

Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Categories

Resources