How to determine if object is in array? - javascript

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
}

Related

Using Javascript Array Filter method to apply logic [duplicate]

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".

How to find if a value matches one of the values from an array in Javascript [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});

Javascript - check if string is part of a string in an array

I have an array which lists a couple of websites:
var validSites = new Array();
validSites[0] = "example_1.com";
validSites[1] = "example_2.com";
validSites[2] = "example_3.com";
now i have a small script which checks what web address you are on and could return something like this:
example_1.com/something/something_else
now i need to check if that address is one of the valid sites.
so
example_1.com/*ANYTHING*
would pass as correct.
but
exampleshmample.com
would pass as incorrect.
Now i know you can do an indexOf() which can check if a string is part of a string and it would return -1 if false. but how would i check it through the entire array?
P.s - its for a Chrome Extension.
thanks
Here’s an idea:
var str = 'example_1.com/something/something_else';
if( validSites.indexOf( str.split('/')[0] ) > -1 ) {
// is valid
}
Another one is to use regexp on a joined array:
var str = 'example_1.com/something/something_else';
new RegExp('^('+validSites.join('|')+')','i').test(str);
This will also match f.ex example_1.comyoyoyo
if (validStates.indexOf("example_1.com") > -1) {
// Then it's inside your array
}
else {
// Then it's not inside your array
}
I'd go with json notation, if you can switch from an array, in this scenario
var validSites = {
"example_1.com":"valid",
"example_2.com":true,
"example_3.com":1 //you could even start putting paths in here to beef up your check.
};
//..your check function would be:
.....
if(validSites[window.location.hostname]){
return true;
}else{
return false;
}
You can achieve this by looping and setting flag variable, Try this, i am not tested this.
Just i typed the code directly. i think this may help you
var flag =0;
var givenurl='example_1.com/*ANYTHING*';
for(int i=0 i<validSites.length;i++){
if(givenurl.indexOf(validSites[i])){
flag=1 //Found
}
}
if(flag) { //Url Found }else{ //not found }

Is there a way that I can check if a data attribute exists?

Is there some way that I can run the following:
var data = $("#dataTable").data('timer');
var diffs = [];
for(var i = 0; i + 1 < data.length; i++) {
diffs[i] = data[i + 1] - data[i];
}
alert(diffs.join(', '));
Only if there is an attribute called data-timer on the element with an id of #dataTable?
if ($("#dataTable").data('timer')) {
...
}
NOTE this only returns true if the data attribute is not empty string or a "falsey" value e.g. 0 or false.
If you want to check for the existence of the data attribute, even if empty, do this:
if (typeof $("#dataTable").data('timer') !== 'undefined') {
...
}
if (typeof $("#dataTable").data('timer') !== 'undefined')
{
// your code here
}
In the interest of providing a different answer from the ones above; you could check it with Object.hasOwnProperty(...) like this:
if( $("#dataTable").data().hasOwnProperty("timer") ){
// the data-time property exists, now do you business! .....
}
alternatively, if you have multiple data elements you want to iterate over you can variablize the .data() object and iterate over it like this:
var objData = $("#dataTable").data();
for ( data in objData ){
if( data == 'timer' ){
//...do the do
}
}
Not saying this solution is better than any of the other ones in here, but at least it's another approach...
Or combine with some vanilla JS
if ($("#dataTable").get(0).hasAttribute("data-timer")) {
...
}
All the answers here use the jQuery library.
But the vanilla javascript is very straightforward.
If you want to run a script only if the element with an id of #dataTable also has a data-timer attribute, then the steps are as follows:
// Locate the element
const myElement = document.getElementById('dataTable');
// Run conditional code
if (myElement.dataset.hasOwnProperty('timer')) {
[... CODE HERE...]
}
You can use jQuery's hasData method.
http://api.jquery.com/jQuery.hasData/
The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.
This will only check for the existence of any data objects (or events) on your element, it won't be able to confirm if it specifically has a "timer" object.
If you want to distinguish between empty values and missing values you can use jQuery to check like this.
<div id="element" data-foo="bar" data-empty=""></div>
<script>
"foo" in $('#element').data(); // true
"empty" in $('#element').data(); // true
"other" in $('#element').data(); // false
</script>
So from the original question you'd do this.
if("timer" in $("#dataTable").data()) {
// code
}
You can create an extremely simple jQuery-plugin to query an element for this:
$.fn.hasData = function(key) {
return (typeof $(this).data(key) != 'undefined');
};
Then you can simply use $("#dataTable").hasData('timer')
Gotchas:
Will return false only if the value does not exist (is undefined); if it's set to false/null it hasData() will still return true.
It's different from the built-in $.hasData() which only checks if any data on the element is set.
You can check by css attribute selection with
if ($('#dataTable').is('[data-timer]')) {
// data-timer attribute exists
}
This is the easiest solution in my opinion is to select all the element which has certain data attribute:
var data = $("#dataTable[data-timer]");
var diffs = [];
for(var i = 0; i + 1 < data.length; i++) {
diffs[i] = data[i + 1] - data[i];
}
alert(diffs.join(', '));
Here is the screenshot of how it works.
I've found this works better with dynamically set data elements:
if ($("#myelement").data('myfield')) {
...
}
Wrong answer - see EDIT at the end
Let me build on Alex's answer.
To prevent the creation of a data object if it doesn't exists, I would better do:
$.fn.hasData = function(key) {
var $this = $(this);
return $.hasData($this) && typeof $this.data(key) !== 'undefined';
};
Then, where $this has no data object created, $.hasData returns false and it will not execute $this.data(key).
EDIT: function $.hasData(element) works only if the data was set using $.data(element, key, value), not element.data(key, value). Due to that, my answer is not correct.
I needed a simple boolean to work with. Because it's undefined of not present, and not false, I use the !! to convert to boolean:
var hasTimer = !!$("#dataTable").data('timer');
if( hasTimer ){ /* ....... */ }
An alternative solution would be using filter:
if( $("#dataTable").filter('[data-timer]').length!==0) { /* ....... */ }
var data = $("#dataTable").data('timer');
var diffs = [];
if( data.length > 0 ) {
for(var i = 0; i + 1 < data.length; i++) {
diffs[i] = data[i + 1] - data[i];
}
alert(diffs.join(', '));
}
And what about:
if ($('#dataTable[data-timer]').length > 0) {
// logic here
}

How to check for {} value in JavaScript?

For some reason in the code below the currentRow.cells returns {}. How can I check for that? I do not want to execute lines if the currentRow.cells returns {}.
currentRow = document.createElement("TR");
if(currentRow.cells.length > 0) { .. do something }
UPDATE 1:
All I want is to check for empty object. if the currentRow.cells is an empty object then do nothing.
I always get an object of type HTMLCollection.
You should be able to then check the length of the collection using code like this:
if(currentRow.cells.length != 0) {
//row and cells exist, work with them
}
jQuery has a helper method called $.isEmptyObject().
Their code for this is simple:
function isEmptyObject( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
If you don't want to use the whole jQuery library, you can snag this method and drop it somewhere in your own code base!
To answer your question in the title:
function is_empty(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i))
return false;
}
return true;
}
alert(is_empty({})); // true
currentRow is a <tr> (or a HTMLTableRowElement), and currentRow.cells is a HTMLCollection (not an Array ([]) or an object ({})).
If currentRow.cells is undefined, that means that current row isn't a <tr>, it's another element.
To check if a DOM element is empty, you can use childNodes (this will never be undefined).
if(currentRow.childNodes.length === 0){
// empty
}
else{
// not empty
}
Edit: Better yet, you can use hasChildNodes.
if(!currentRow.hasChildNodes()){
// empty
}
else{
// not empty
}
cells property isn't available in <tr> on IE8 and below. A workout is to use childNodes as suggested above. The following code checks if cells is undefined:
var currentRow = document.createElement("TR");
if (typeof currentRow.cells === "undefined") {
// use currentRow.childNodes
}
else {
// use currentRow.cells
}

Categories

Resources