javascript find if value is NOT IN array - javascript

My problem with this is that the loop keeps going into the if statement even for duplicate barcodes. I'm trying to enter the if statement only for unique barcodes but at the end of the loop myArray has duplicates in it....why?
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( !( iBarCode in myArray ) ){
myArray[i++] = iBarCode;
//do something else
}
});

Jquery has an inArray() function.
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( $.inArray(iBarCode, myArray) == -1 ){
myArray[i++] = iBarCode;
//do something else
}
});

The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.
You should instead use an array search function as Gazler advises.

2021 Update
let myArray = [...new Set([...document.querySelectorAll('li.foo')].map(a => a.dataset.barcode))]
Working backwards: Create an array using the spread syntax from the matching elements, which Map only the data-barcode attribute. Use that to create a new Set, then create an array from that set

Related

Array of functions cleanup of empty slots

im having a problem, i have a array of functions which is frequently added to and removed from.
But when i do a foreach on the array it says that the index don't exist.
Input:
arr[arr.length] = function () { Func() };
Remove:
delete arr[indexToRemove];
for don't work now so i use a foreach
for (key in arr)
I'm getting a feeling that it is possible to overflow on the index so to prevent this i would like to find empty array positions and reposition the items in it.
This is what I'm thinking for cleanup atm.
var temp = new Array();
var count = 0;
for (key in arr) {
if (arr[key] != null) {
temp[count] = arr[key];
count++;
}
}
arr = temp;
Is there a better solution and does a empty array of functions slot look like null?
Don't use a for...in loop to iterate over an array; use a standard counting for loop. Do use Array.push() instead of arr[arr.length] = cont to add new values. Also don't use delete to remove an element from an array; use Array.splice().
Input: arr.push(cont);
Remove: arr.splice(indexToRemove, 1);

jQuery/Javascript if value is in array, continue

I have data that is in an array, these are the ID's for users that have commented on said post. I want to compare this array with the id of the user, and if their id is in this array, continue with the code.
my array looks like:
({0:"1", 3:"6"}) // 1 and 6 are the ID's that I want to work with.
So I want to do something like:
var array = ({0:"1", 3:"6"});
var userID = 6;
if(in(array)==userID)
{
///you are in the list, so do whatever
}
Instancing your array like that will not create an array, but an object. Normally, you instantiate arrays in javascript like this:
var arr = [17, 4711];
Checking for a value using Array.indexOf:
arr.indexOf(17); // => 0
arr.indexOf(4711); // => 1
arr.indexOf(42); // => -1
Pushing:
arr.push(42);
arr.indexOf(42); // => 2
Array.indexOf is not in IE < 9, so I suggest you look into using a shim.
function inArray(needle, haystack) {
var count = 0;
for (var k in haystack) {
if (haystack.hasOwnProperty(k)) {
++count;
}
}
for (var i in haystack) {
if(haystack[i] == needle) return true;
}
return false;
}
​
See : http://jsfiddle.net/ryN6U/1/
If will not work with your object :)
You can loop through your object and check it against your userid. Something like
$(document).ready(function(){
var myArray = ({0:"1", 3:"6"});
var userId = 6;
for(vals in myArray){
if(userId == myArray[vals]){
alert("userid exists in array");
}
}
});
When testing against an array I would use jQuery's inArray()
if your looking for the first item in an object with a certain value look at this thread
json index of property value

Javascript multidimentional array undefined object error

I am trying to make a two dimensional array out of two one dimentional arrays with this code:
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
However, I get the error message: " 'undefined' is null or not an object " and it points to the first line after the for statement.
PassPourcentNames and PassPourcentValue have the same number of elements and none of the values are null. The first one contain strings and the second one integers.
Any help is greatly apreciated.
var PassAssoArr = new Array();
for(k in PassPourcentNames) {
PassAssoArr[k] = new Array();
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
Also instead of new Array() you can use []
var PassAssoArr = [];
for(k in PassPourcentNames) {
PassAssoArr[k] = [];
PassAssoArr[k][0] = PassPourcentNames[k]
PassAssoArr[k][1] = PassPourcentValue[k]
}
I believe this is actually faster in most JS engines.
First define PassAssoArr[k] = []; before assigning to [0] and [1].
Javascript does not support true multi-dimensional arrays.
You're trying to use nested arrays without creating the inner arrays.
You need to put an array into each element of the outer PassAssoArr:
PassAssoArr[index] = []; //Empty array literal
You're only defining one dimension of PassAssoArr - you need to set PassAssoArr[k] = new Array();
Try just doing:
PassAssoArr[k] = new Array(PassPourcentNames[k], PassPourcentValue[k]);

Javascript VAR syntax

What does this mean in var definition:
var array = array || [];
... and next two parts of javascript are equal each other?
var array = array || [];
array.push([1],[2]);
array.push([3]);
=
var array = array.push([1],[2],[3]) || [];
?
The first statement will set array to an empty array if it is a falsey value (null, undefined, etc.).
The next two parts are not equal, and will likely fail when you try to call push on something that is not known to be an array.
It is equivalent to this,
var array;
if(array){
array = array;
} else {
array = [];
}
Just in a much shorter form.
In the second part, No those two are not equivalent.
array.push([1],[2],[3])
needs to be executed no matter what, if you use || [] it will not be added.
In other words, you start with this,
var array;
if(array){
array = array;
} else {
array = [];
}
array.push([1],[2],[3]);
And you then modified it to this,
var array;
if(array){
array = array;
array.push([1],[2],[3]);
} else {
array = [];
}
It means that if array is a falsy value (undefined, null etc.) - the value that will be assigned to the var array is an empty array - [];
EDIT:
the second part of your question - no these are not equivalent.
For instance, when array is undefined:
var array = array.push([1],[2],[3]) || [];
this will throw an exception.
This:
var array = array || [];
array.push([1],[2]);
array.push([3]);
will not.
It's setting the var to a new array if it's not defined.
That syntax uses the javascript boolean or operator, and its evaluation of truthy/falsey statements to provide a valid default value.
So
var array = array || [];
Means "use an empty array if array evaluates false".

Getting undefined value from an array

Talk is cheap; I'd rather show the code:
//global var
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined
Why undefined? What I basically want to achieve is to have a global object that would be a storage where info about other objects get saved. But get back to my problem. I pushed the value then I want to alert it but get undefined... why undefined?
.push appends it to the array, siblings[0] contains it because it's the first element in (formerly) empty array.
If you want to determine the key yourself, do
siblings = {};
siblings['key'] = 'something';
Otherwise loop through the array if you want to access each element
for ( var l = siblings.length, i = 0; i<l; ++i ) {
alert( siblings[i] )
}
Note: arrays are objects so I could've set siblings['key'] = 'something'; on the array, but that's not preferred.
siblings is an array. You're pushing the value 'uin_'+rand onto it, so the keys would then be 0. Instead, you'd want to create an object.
var siblings={};
var rand=+new Date();
siblings['uin_'+rand]="something";
alert(siblings['uin_' + rand]);
Because you pushed a string value to array index 0, then tried to get a non-existant property on the array object.
Try using Array.pop().
In order to access an array, you need to use array indices, which basically refer to whether you want the 1st, 2nd, 3rd, etc.
In this case, use siblings[0].
Because siblings is an array, not an associative array. Two solutions:
//global var - use as an array
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings[0]); // undefined
//global var - use as an associative array
var siblings = {};
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined

Categories