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) });
Related
variants is an object of objects and selectedOptions is an object of option1, option2, option3. The below forEach searches through the variants to find a match.
Is there a more efficient way, using an array method or similar, to do the following:
Object.values(variants).forEach(variant => {
if (variant.options.option1 === selectedOptions.option1 && variant.options.option2 === selectedOptions.option2 && variant.options.option3 === selectedOptions.option3) {
selectedVariant = variant.gid;
}
});
One thing you're doing here is loop through all the variants, overwriting selectedVariant each time you find a match. And if there's supposed to be only one match, you still visit all the other variants when there's no need for it anymore.
More efficient would be:
selectedVariant = Object.values(variants).find(variant => (
variant.options.option1 === selectedOptions.option1 &&
variant.options.option2 === selectedOptions.option2 &&
variant.options.option3 === selectedOptions.option3
)).gid;
That way you stop the moment you find a match.
And to be perfectly honest, setting a variant equal to another variant's gid looks wrong. Either name the variable you assign to selectedVariantGid, or assign the entire variant, and later use the .gid property once you need it. Clear naming is important.
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.
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
I am pretty sure there is a better way of doing this. In the code below, I am trying to set the value of item object inside selected_items array. I've discovered that using '=' instead of '==' returned an altered version of the found object (a behavior that I found useful in other parts of my code).
Is this a good idea? I would really like to know a cleaner way of doing this using lodash.
$scope.increase_item_quantity = function(item_pk, addition){
if($scope.is_item_selected()){
var item_quantity = $scope.get_item_quantity();
if(!(item_quantity < 1 && addition == -1)){
console.log('adding...')
$scope.selected_items = _.result(_.find($scope.selected_items, function(item) {
return item.quantity = addition;
}), 'quantity');
}
}
}
Via the method above, I am trying to set the quantity of the item with a particular id.
Simple vanilla js
$scope.selected_items.forEach(function(item){
item.quantity = new_quantity;
});
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;
});