Check a variable with multiple values in jquery - javascript

I need to check if a variable in if condition as follows.
if(table_block_id == ('customer_details' || 'billing_details' || 'shipping_details')){
}
I know it's the wrong method . Is there any other way to check all values in a single line ?

The easiest way would be to use Array.prototype.includes as EKW suggested in his answer.
However, due to its poor support I would recommend using Array.prototype.indexOf instead:
if(["customer_details", "billing_details", "shipping_details"].indexOf(table_block_id) !== -1){
// code
}

There are a few methods you could use. I quite like the following:
if(["customer_details", "billing_details", "shipping_details"].includes(table_block_id)){
// code
}

You can put the options in array and use jQuery $.inArray() or javascript indexOf() to search array.
var a = 'customer_details';
arr = ['customer_details', 'billing_details', 'shipping_details'];
if($.inArray(a, arr) != -1) // With jQuery
//code
else
//code

Related

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

_.findWhere from underscorejs to JQuery

I am trying to implement this code: http://jsfiddle.net/wQysh/351/ in my project.
Everything is fine except for the line:
t = _.findWhere(sc, { id : Number(a.trim()) });
They have used underscorejs and I want to translate this to JQuery without using another lib.
I went through the doc and it stated:
findWhere_.findWhere(list, properties)
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.
If no match is found, or if list is empty, undefined will be returned.
But still I am confused about this since I am not sure what to return exactly (as first value). Can anyone give me a JQuery alternative to that line?
Thanks in advance..
If you don't the generic nature of _.findWhere() you can use a simple while loop, and compare the id to the numeric value of a (fiddle):
t = 0; // t is used as a counter
aValue = Number(a.trim()); // assign the value to a variable instead of iterating it
while (t < sc.length && sc[t].id !== aValue) { t++; }; // find the index where the id is the as the aValue
t < sc.length && toSet.push(sc[t]); // if t is less the sc.length we found the item in the array
If you need a findWhere without underscore try this gist.
I also used this example in my project. And also needed use JQuery instead of Underscore.
Here is my solution:
t = sc.filter(function (el) { return el.id === a });
It work perfect for me;
If you use number for ids, you can also convert a to integer
t = sc.filter(function (el) { return el.id === parseInt(a, 10) });

Javascript What method should I use to find or check if a string exists in an array?

I found these methods, indexOf() apparently doesn't work for internet explorer 8
There are a lot of options, I want to know which one is like the defacto or what I should opt to use for best results.
Also, if the result is undefined, how do I use that as a value do I simply use it as a string like "undefined" or is it null?
array.find()
array.findIndex()
array.indexOf("string");
In this example of replacing a string within an array knowing the index, they use indexOf, should I be concerned of incompatibility?
var index = items.indexOf(3452);
if (index !== -1) {
items[index] = 1010;
}
It's perfectly acceptable to use a polyfill for these types of things:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
if (!Array.prototype.indexOf) {
// paste polyfill here
}
You could also use methods provided by different libraries:
// jQuery
if ($.inArray("some_value", someArray) > -1) { ... }
// Underscore
if (_.contains(someArray, "some_value")) { ... }

basic coffeescript find if in array

In coffee script I'm trying to figure out if something is included in an array or not. But can't seem to figure out the correct syntax. Is there not a way to do this without have to iterate over them?
Thanks,
if $(this).val() is in ["needs_cover","comatose"]
$("#head_count").hide()
else
$("#head_count").show()
Just drop the is:
if $(this).val() in ["needs_cover","comatose"]
$("#head_count").hide()
else
$("#head_count").show()
That would translate to the following JavaScript:
var _ref;
if ((_ref = $(this).val()) === "needs_cover" || _ref === "comatose") {
$("#head_count").hide();
} else {
$("#head_count").show();
}
If this is a common use case, you could write a function, which would also allow you to write a routine that is a bit more compact as well, like so:
hideShowFn = (valSelector, hideShowElSelector, compareArr) ->
if $(valSelector).val() in compareArr then return $(hideShowElSelector).hide()
$(hideShowElSelector).show()
I prefer doing the above as it flattens the code a little bit. This is my preference.
You would call the function like so:
hideShowFn this, '#head_count', ['needs_cover', 'comatose']

how to break the _.each function in underscore.js

I'm looking for a way to stop iterations of underscore.js _.each() method, but can't find the solution. jQuery .each() can break if you do return false.
Is there a way to stop underscore each()?
_([1,2,3]).each(function(v){
if (v==2) return /*what?*/;
})
You can't break from the each method—it emulates the native forEach method's behavior, and the native forEach doesn't provide to escape the loop (other than throwing an exception).
However, all hope is not lost! You can use the Array.every method. :)
From that link:
every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false.
In other words, you could do something convoluted like this (link to JSFiddle):
[1, 2, 3, 4].every(function(n) {
alert(n);
return n !== 3;
});
This will alert 1 through 3, and then "break" out of the loop.
You're using underscore.js, so you'll be pleased to learn that it does provide an every method—they call it every, but as that link mentions, they also provide an alias called all.
Update:
_.find would be better as it breaks out of the loop when the element is found:
var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){
count = count +1;
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1
** Old **
If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet
var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//output: {id:1,text:"foo"}
You can have a look to _.some instead of _.each.
_.some stops traversing the list once a predicate is true.
Result(s) can be stored in an external variable.
_.some([1, 2, 3], function(v) {
if (v == 2) return true;
})
See http://underscorejs.org/#some
_([1,2,3]).find(function(v){
return v if (v==2);
})
Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.
Like the other answers, it's impossible.
Here is the comment about breaker in underscore underscore issue #21
You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.
I believe if your array was actually an object you could return using an empty object.
_.({1,2,3,4,5}).each(function(v){
if(v===3) return {};
});
It's also good to note that an each loop cannot be broken out of — to
break, use _.find instead.
http://underscorejs.org/#each
Update:
You can actually "break" by throwing an error inside and catching it outside: something like this:
try{
_([1,2,3]).each(function(v){
if (v==2) throw new Error('break');
});
}catch(e){
if(e.message === 'break'){
//break successful
}
}
This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!
worked in my case
var arr2 = _.filter(arr, function(item){
if ( item == 3 ) return item;
});

Categories

Resources