I have a array of objects say items. I want to find item having name xyz.
Currently, I wrote a for loop
for(var i = 0; i < items.length; i++)
{
if( items[i].name == "xyz" )
{
found = true;
break;
}
}
Is it possible to shorten this loop to one line statement using jquery? something like this:
$.find(items, "name", "xyz");
You might use
var matchingItems = items.filter(function(v){return v.name=="xyz"});
or using jQuery (for greater compatibility, as like many Array functions, filter or some aren't available on IE8) :
var matchingItems = $.grep(items, function(v){return v.name=="xyz"});
Something like:
$.grep(yourArray, function(n) {
return n.name == "xyz";
});
Use the native some method:
items.some(function(el) { return el.name == "xyz"; })
With jQuery, you would need to do something like $.grep and then check the length ($.grep(items, function(el){ return el.name=="xyz"; }).length > 1) - not an optimal solution. If you want to use a library solution for those browsers that don't support some (and don't want to use the polyfill), use Underscore's any.
var arr = ["abc", "xyz" ];
if($.inArray("abc",arr) > 0){
return true;
}
else
return false
this will return the index of "searching string"
if not found, it will return -1.
Use jQuerys inArray Example
http://api.jquery.com/jQuery.inArray/
might helps you
(function( $ ) {
$.find = function( array, property, key ) {
var found = false;
for(var i = 0; i < array.length; i++)
{
if( array[i][property] == key )
{
found = true;
break;
}
}
return found ? i : -1;
};
})( jQuery );
Usage: $.find(items, "name", "xyz");
Related
So the variable classList stores all classes for the body. I then created a variable classListLength that has the length of classList so I can iterate through each index and then split each class. I do not know how to store the splits for each index as it loops through classList. Help me please.
var classList = jQuery('body').attr('class').split(' ');
var classListLength = classList.length;
var keyWords = function(array) {
for (var i = 0; i < classListLength; i++ ) {
classList[i].split('-');
}
}
if i do the following in the console
var keyWords = function(array) {
for (var i = 0; i < classListLength; i++ ) {
console.log(classList[i].split('-'));
}
}
I can see exactly what I want but I want to be able to store that and check it later on with a conditional.
var splitClassList = classList.map(function (class) {
return class.split('-');
});
So I solved what I needed. The below code allows me to iterate through my split classList. I then check the the specific class I want within the classList using .includes method and execute what I need done. If you guys know how to make this a bit more modular please chime in.
var brandClass
// Iterate though split classes
jQuery.each( classList, function(i) {
if ( classList[i].includes('product-wildridge') ) {
brandClass = classList[i];
}
});
// check specific class for certin keywords
var customTab = function(brandClass) {
if (brandClass.includes('wildridge') && brandClass.includes('deep') ) {
return true;
} else {
jQuery('#tab-fabric').css('display', 'none');
}
}
customTab(brandClass);
I have a javascript array that looks like this:
myFields = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-location","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
]
I'm able to loop through the array and deal with specific bits like this:
len = fields.length;
//first check to make sure required fields are filled in
for(i=0; i<len; i++) {
a = fields[i];
if(a[0] != "fb-method") {
// do stuff
}
}
I need to be able to (outside the loop) do something if a specific element isn't part of the array, specifically one that looks like this:
["fb-location","drop",false,""]
I've tried using jQuery's .inArray function, but it returns true even when it should return false. See fiddle here.
What's the best way to go about this? jQuery or standard js is fine.
$.inArray does not return a bool, it returns the index (if no match exists, it returns -1). You would want this statement (based on your jsfiddle):
if(jQuery.inArray("fb-location", tmp) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO:
http://jsfiddle.net/azWLC/2/
UPDATE:
As mentioned in the comments, this is only a half solution since the array is multidimensional. I recommend first using $.map():
var tmp = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
];
var values = $.map(tmp, function(n, i){
return n[0];
});
if(jQuery.inArray("fb-location", values) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO:
http://jsfiddle.net/azWLC/4/
jquery.inArray returns the index of the element. If it is not found it returns -1.. And any number except 0 is true and hence it says 'it exists'
Besides $.inArray you could use Array.filter on tmp this way:
if( tmp.filter(function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
JsFiddle
See also: Array.filter, Array.indexOf
Using JQuery, you'd use the JQuery grep method
if( $.grep(tmp,function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
There's a gap in my JavaScript knowledge here. I want to search an array of objects values for a particular value and return it.
For the year I have been writing JavaScript, I have been implementing it like this:
var itemClicked = (function(){
var retval;
//Note self.inventory.itemsArray is an array of JS objects
$(self.inventory.itemsArray).each(function(i){
if(parseInt(this.id) === parseInt(idOfItem)){
retval = this;
return false;
}
});
return retval;
})();
It works, but I'm sure as anything there is a more elegant way. Tell me please!
EDIT - Solution
Thanks to #gdoron with his answer below.
var myVar = $(self.owner.itemsArray).filter(function(){
return parseInt(this.id) == parseInt(recItemID);
}).get(0);
Note: .get(0) was added at the end because myVar is wrapped as a jQuery object.
The native jQuery function for this is filter:
$(data).filter(function(){
return this.id == "foo";
});
It's shorter than code you have and more important a lot more readable.
About efficiency, it will iterate all the elements in the set to find as much as possible matches, but I hardly believe it will be the bottle neck of your application, don't focus on micro-optimisations.
I suggest you read Eric Lipper blog about Which is faster.
You can also use grep as suggested by #Mattias Buelens:
$.grep(data, function(ele){
retun ele.id == "foo";
});
Just another option using jQuery's $.grep( ) function
var arr = $.grep( self.inventory.itemsArray, function ( n ) {
return n.id == idOfItem;
});
The above returns an array of matching array elements. If you just want the first it is easy enough to return arr[0] if it exists.
Although I'm unsure what the function is actually supposed to do (due to the external contexts' variables), the following should be more efficient cycle-wise
var itemClicked = (function(){
var i, array = self.inventory.itemsArray, length = array.length;
for( i=0; i < length; i++) {
if(parseInt(array[i].id) === parseInt(idOfItem)){
return array[i];
}
}
return undefined;
})();
It's an array of Javascript objects
Then do not use jQuery at all. At least, use $.each instead of building a wrapper object around the array. Still, a simple for-loop is much shorter and more performant:
var itemClicked = (function(idnum) {
var arr = self.inventory.itemsArray;
for (var i=0, l=arr.length; i<l; i++)
if (parseInt(arr[i].id, 10) === idnum)
return arr[i];
})( parseInt(idOfItem, 10) );
You might as well think of storing the id properties as numbers right away, so you don't need to convert it each time.
I'm trying to set up an IF statement if a value is contained within an array.
I've found some code which claimed to work but it doesn't seem to be.
var myAsi = ['01','02','24OR01','30De01','9thC01','A.Hu01','A01','AACAMSTE','ABBo01','ABBo02','ABC-01','ACCE01','Acce02','AceR01','h+dm01','Merr02','Ofak01','Wage01','Youn01'];
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
var resultHtml = '';
resultHtml+='<table style ="width: 400px">';
resultHtml+='<tr colspan="2">';
resultHtml+='<td colspan="2">';
resultHtml+='<b><font color = "Red">(Client Code)</font><br><font color = "green">(Company Name)</font></b>';
resultHtml+='</td>';
resultHtml+='</tr>';
$.each(data, function(i,item){
resultHtml+='<div class="result">';
resultHtml+='<tr>';
if (notFound=myAsi.find("'"+item.code+"'") == false) {
resultHtml+='<td>';
}
else {
resultHtml+='<td bgcolor=#D8D8D8>';
}
resultHtml+='<font color = "red">'+item.code+'</font><br>';
resultHtml+='<font color = "green">'+item.content+'</font></td>';
resultHtml+='<td style ="width: 80px">Remove - ';
resultHtml+='Add';
resultHtml+='</td>';
resultHtml+='</tr>';
resultHtml+='</div>';
});
resultHtml+='</table>';
The item.code cycles through and I need an IF statement to tell me if it appears within the array.
Any help would be great.
If you only want to find if an item is in an array you could use a simpler function than that. For eg. the jQuery implementation:
// returns index of the element or -1 if element not present
function( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
This uses the native browser implementation of indexOf if available (all browsers except IE I think), otherwise a manual loop.
Try removing the apostrophes from your find() call. eg
notFound=myAsi.find(item.code)
Though actually, for your purposes see this example which uses this function....
Array.prototype.find = function(searchStr) {
for (var i=0; i<this.length; i++) {
if (this[i]==searchStr) return true;
};
return false;
};
And as an aside - Be very careful about using var before using a variable - otherwise you create a global variable (which you probably don't want). ie the line in your original function....
for (i=0; i<this.length; i++)
i is now global...
Array.prototype.contains = function(value, matcher) {
if (!matcher || typeof matcher !== 'function') {
matcher = function(item) {
return item == value;
}
}
for (var i = 0, len = this.length; i < len; i++) {
if (matcher(this[i])) {
return true;
}
}
return false;
};
This returns true for elements in the array that statisfy the conditions defined in matcher. Implement like this:
var arr = ['abc', 'def', 'ghi']; // the array
var valueToFind= 'xyz'; // a value to find in the array
// a function that compares an array item to match
var matcher = function(item) {
return item === matchThis;
};
// is the value found?
if (arr.contains(valueToFind, matcher)) {
// item found
} else {
// item not found
}
UPDATES:
Changed the contains method to take a value and an optional matcher function. If no matcher is included, it will do a simple equality check.
Test this on jsFiddle.net: http://jsfiddle.net/silkster/wgkru/3/
You could just use the builtin function
['a','b','c'].indexOf('d') == -1
This behavior was mandated in the javascript specification from over 6 years ago. Though I gave up on Internet Explorer for these reasons at around IE8, because of this incredibly poor support for standards. If you care about supporting very old browsers, you can use http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/ to tack on your own custom Array.indexOf
I don't recall IE9 supporting [].indexOf, but Microsoft claims it does: http://msdn.microsoft.com/en-us/library/ff679977(v=VS.94).aspx
The standard way to determine the index of the first occurence of a given value in an array is the indexOf method of Array objects.
This code checks if it this method is supported, and implements it if not, so that it is available on any Array object:
if(Array.prototype.indexOf==null)
Array.prototype.indexOf = function(x){
for(var i=0, n=this.length; i<n; i++)if(this[i]===x)return i;
return -1;
};
Now myArray.indexOf(myValue) returns the first index of myValue in myArray, or -1 if not found.
I have a three strings of categories
"SharePoint,Azure,IT";
"BizTalk,Finance";
"SharePoint,Finance";
I need to find a way to check if a string contains for example "SharePoint" and "IT", or "BizTalk" and "Finance". The tests are individual strings themselces.
How would i loop through all the category strings (1 - 3) and only return the ones which have ALL instances of the souce.
i have tried the following
function doesExist(source, filterArray)
{
var substr = filterArray.split(" ");
jQuery.each(substr, function() {
var filterTest = this;
if(source.indexOf(filterTest) != -1 )
{
alert("true");
return true;
}else
{
alert("false");
return false;
}
});
}
with little success...the code above checks one at a time rather than both so the results returned are incorrect. Any help would be great.
Thanks
Chris
UPDATE: here is a link to a work in progress version..http://www.invisiblewebdesign.co.uk/temp/filter/#
Try this:
function doesExist(source, filter)
{
var sourceArray = source.split(",");
var filterArray = filter.split(",");
var match = true;
$.each(filterArray, function(i, val) {
match = match && ($.inArray(val, sourceArray) != -1);
});
return match;
}
gives doesExist("SharePoint,Azure,IT", "SharePoint,IT")==true but doesExist("SharePoint,Azure,IT", "SharePoint,BizTalk")==false.
you could try something like:
if(filterArray.indexOf("SharePoint") > -1 && filterArray.indexOf("IT") > -1) {
...
}