Remove an item from array of items - javascript

I have list of variables/items
dbTemp = [Type,Threshold,TypeID,Prioirty,Value,Assign]
where Type,Threshold,TypeID,Prioirty are variables
Let's say, their values are 1,0,2,0,NULL,21
If a variable value is 0 or NULL, I need to remove/exclude them from the list and build a dynamic variable expression based on the non-zero or non-NULL values
In this case, Dynamic Expression = Type>0+TypeID>0+Assign>0 (excludes Threshold, Priority, Value variables since their values are 0 or NULL)
Can you please help me here?

filtered here:
var filtered = dbTemp.filter( function(el) { return !!el; } );
will contain all non null or zero elements from dbTemp;

If you want to filter based on some condition(s) instead of just filtering falsy values:
var filtered = orignalArray.filter(function(item) {
return (item !== condition1) && (item !== condition2);
});
p.s. NULL !== null

If you'll allow for any falsey value and a result that is a filtered copy, then this will suffice:
var result = dbTemp.filter(Boolean);
If you actually need to mutate the original and order doesn't matter, then do this:
for (var i = 0; i < dbTemp.length; i++) {
if (!dbTemp[i]) {
dbTemp[i] = dbTemp[dbTemp.length-1];
dbTemp.length--;
i--;
}
}
If the original order does matter, then this:
for (var i = 0; i < dbTemp.length; i++) {
if (!dbTemp[i]) {
dbTemp[i].splice(i, 1);
i--;
}
}

Related

Arrays in arrays, length always is 0, json not working

I try to create arrays in arrays and then forward it to JSON.
First problem, when i try to use a lista.length or something, console always return 0. I tried to overpass this problem and create another array, but now I have problem with JSON - always return [] - empty lista array.
var lista = [];
var licz = [];
function ListujBledy(value, where) {
var checked = document.getElementById(value).checked;
var desc;
if (value == "blad-tab") {
desc = "Nieprzeźroczysta lista graczy.";
} else if (value == "blad-tab1") {
desc = "Brak listy graczy na początkowym zrzucie ekranu.";
} else if (value == "blad-tab2") {
desc = "Brak listy graczy na końcowym zrzucie ekranu.";
}
if (checked == true) {
if (lista[where] == undefined) {
var temp = [];
temp[value] = desc;
lista[where] = temp;
licz[where] = 1;
} else if (licz[where] == 1) {
var temp = lista[where];
temp[value] = desc;
lista[where] = temp;
licz[where] = 2;
} else if (licz[where] == 2) {
var temp = lista[where];
temp[value] = desc;
lista[where] = temp;
licz[where] = 3;
}
} else {
if (licz[where] == 1) {
delete lista[where];
licz[where] = 0;
} else if (licz[where] == 2) {
delete lista[where][value];
licz[where] = 1;
} else if (licz[where] == 3) {
delete lista[where][value];
licz[where] = 2;
}
}
console.log(lista.length);
console.log(lista);
console.log(JSON.stringify(lista));
console.log("---------------------------------------------------------");
}
Console log from browser:
I don't have more ideas, I can't use lista[0], lista[1] etc. everything must be functional. Eveyrthing is taken from variables but everywhere I was looking for information about it, everybody using numbers in key or permanent keys.
Editied version of code:
I know that checked could have been better done, so I corrected it here.
https://jsfiddle.net/5vdgLtue/1/
The main problem is that even if I do this https://jsfiddle.net/5vdgLtue/0/ the array returns this element, but the length function says it is 0.
It looks like you might be starting out with javascript. Keep in mind that you haven't actually called the function at any point in your code. Is that the case or are you not sharing the full code you have run?
There is only one condition in which the array 'lista' could gain value: if 'check'== true and 'where' == undefined.
In that scenario, you declare the array 'temp' and declare temp[value]= desc. However, if 'value' contains a value different than "blad-tab", "blad-tab1" or "blad-tab2", 'desc' remains empty therefore temp[value] has a name but no value. You are then assigning a named valueless item to lista[where] which would explain why your console displays content but no length. btw, this would be easier if you named your variable something other than 'value' .
Problem is your selector points to the parent element. In jquery you could do this less code but assuming you're not using jQuery. Try something like:
function getDesc(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
//or use getElementsbyClassName...
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
for (var i=0; i<checkboxesChecked.length; i++) {
if (checkboxesChecked[i].value === "blad-tab") {
desc = "Nieprzeźroczysta lista graczy.";
} else if (checkboxesChecked[i].value === "blad-tab1") {
desc = "Brak listy graczy na początkowym zrzucie ekranu.";
} else if (checkboxesChecked[i].value === "blad-tab2") {
desc = "Brak listy graczy na końcowym zrzucie ekranu.";
}
}
return desc;
}
This should answer most of your questions.
In summary:
In javascript there are 2 types of arrays: standard arrays and associative arrays
[ ] - standard array - 0 based integer indexes only
{ } - associative array - javascript objects where keys can be any strings
What you are doing is using array in an associative manner. Basically, you are adding properties to your array objects, unlike a standard array where you would only assign values by zero-indexed numbers like temp[0]='something', lista[1]='some other thing' etc.
If you want the length of the key set of the array, then you can use Object.keys(lista).length. This should solve your problem.

How to insert a string in an array with a specific order

So I have the following array :
let array = ['9h00','9h30','9h45','10h00','10h15']
Let's say I want to insert '9h15' between '9h00' && '9h30'
How would one do it in a fast & efficient solution ?
EDIT: I have been unclear, the index of the insert would change depending on the array. It won't always be the following position : array[1].
Thanks in advance!
If every item has the same format (\d?\d)h(\d{2}) then we can do the following :
First we need a function to convert the string to an object or something we can work with, I'll go with an object :
function timeStringToObj(str){
var re = "^(\d?\d)h(\d\d)$";
var h = str.replace(re, "$1");
var m = str.replace(re, "$2");
return {
hours: parseInt(h),
minutes: parseInt(m)
};
}
Then we will need to ensure that the array is sorted, for instance "9h15" < "9h16" therefore "9h15"'s index is < "9h16"'s index , (if not use array.sort(/*some sorting function if necessary*/)) and loop through it to find the spot (I'll use a function of course), I'll consider your array as a global variable :
/**
*#param timeObjA an object that is the return value of a call of timeStringToObj
*#param timeObjB an object that is the return value of a call of timeStringToObj
*/
function AgeB(timeObjA, timeObjB){//A greater than or equal to B
return (timeObjA.hours >= timeObjB.hours && timeObjA.minutes >= timeObjB.minutes);
}
/**
*#param a an object that is the return value of a call of timeStringToObj
*#param b an object that is the return value of a call of timeStringToObj
*/
function AleB(a, b){//A less than or equal to B
return (timeObjA.hours <= timeObjB.hours && timeObjA.minutes <= timeObjB.minutes);
}
function putInTimeArray(str){
var val = timeStringToObj(str);
for(let i = 0 ; i < array.length ; i+=1){
var curr = timeStringToObj(array[i]);
//first check : elem >= last
if( AgeB(val, curr) && i===(array.length-1) ){
array.push(str);
return true;
}
//second check : elem <= first
if( AleB(val, curr) && i===0 ){
array.unshift(str);
return true;
}
//last check : first < elem < last
if(i!=0 && i!=(array.length - 1)){
if(AgeB(val, curr)){
array.splice(i+1,0,str);
return true;
}
if(AleB(val, curr){
array.splice(i-1,0,str);//here i-1 is safe since i!=0 (condition)
return true;
}
}//end of last check
}//end of for-loop
}//end of function
If you're having doubts regarding my usage of splice please refer to this : How to insert an item into an array at a specific index?
EDIT
You'll probably need a more sophisticated regex to be more appropriate be this will do the job just fine if you don't go that crazy with those strings
You can push and sort like:
array.push("9h15").sort().reverse(); // ["9h45", "9h30", "9h15", "9h00", "10h15", "10h00"]

need help understanding using an associative array to keep track of array value appearances

code:
method = function(a) {
//use associative array to keep track of the total number of appearances of a value
//in the array
var counts = [];
for(var i = 0; i <= a.length; i++) {
if(counts[a[i]] === undefined) {
//if the condition is looking for a[0],a[1],a[2],a[3],a[4],a[5] inside counts[] one value at a time and does not find them inside counts[] it will set each value to 1
counts[a[i]] = 1;
console.log(counts[a[i]]);
} else {
return true;
}
}
return false;
}
the js console logs 1x6
how can the condition see if a value inside counts[a[i]] has been repeated if all of the counts[a[i]] values are being set to 1 each iteration? wouldn't it always be comparing 1 to 1?
for example, if the a array is [1,2,3,4,5,2] and counts[a[1]](first int 2 in the array) is undefined and then set to 1, how would the condition know that counts[a[5]](second int 2 in the array) is the same value as counts[a[1]] and therefore it should return true?
perhaps I am misunderstanding whats going on.
I would appreciate any help. thanks
function counter(){
this.counts=[];
}
counter.prototype.add=function(a){
if(this.counts[a] === undefined) {
this.counts[a] = 1;
console.log(this.counts);
} else {
return true;
}
return false;
}
try this:
c= new counter();
c.counts;//[]
c.add(1);
c.counts;//[ ,1]
c.add(5);
c.counts;//[ ,1, , , ,1]
c.add(1);//true
...
may it helps you to understand whats going on

How can I skip a specific Index in an array in a for loop javascript

Suppose I had a function that is pulling in values from somewhere and storing those values into an array.
function getSport(ply) {
some code here... //function gets values that I need for array later
}
var sports1 = getSport(playerChoice);
var sports2 = getSport(playerChoice);
var sports3 = getSport(playerChoice);
var sports4 = getSport(playerChoice);
var sportsArry = [sports1, sports2, sports3, sports4];
Now I would like to use a for loop to loop the elements, the problem, however, is the first index (index 0) will always be true. I want to skip index 0. How do I do that? Further I want to replace index 0 with something else. Let me show you
for (var i = 0; i<sportsArry.length; i++){
if ( (sports1 == sportsArry[i]) ) {
sports1 = null; //I figured I should null it first?
sports1 = replaceValueFunc(playerChoice2);
}
}
Well you can see the problem I would have. Index 0 is true.
Let me show you what would work, although it requires alot of or operators.
if ( (sports1 == sportsArry[1]) || (sports1 == sportsArry[2]) || (sports1 == sportsArry[3] ) {
...
}
^^ That is one way to skip index 0, what would be another better looking way?
I want to skip index 0. How do I do that? Further I want to replace
index 0 with something else.
Just start the loop from 1 instead of 0
sportsArr[0] = "Something else"; // set the first element to something else
for(var i = 1; i < sportsArr.length; i++){
// do something
}

Does JavaScript or jQuery have a function similar to Excel's VLOOKUP?

Do JavaScript or jQuery have a function that returns the element of an array whose index equal to the position of a given value in another array? (I could write my own, but I don't want to reinvent the wheel.)
Something like:
function vlookup(theElement, array1, array2) {
$.each(array1, function(index, element) {
if (element === theElement)
return array2[index];
});
return null;
}
But, um... in the standard library.
Something like this perhaps?
Array.prototype.vlookup = function(needle,index,exactmatch){
index = index || 0;
exactmatch = exactmatch || false;
for (var i = 0; i < this.length; i++){
var row = this[i];
if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1)
return (index < row.length ? row[index] : row);
}
return null;
}
Then you can use it against a double array, like so
Depending your purpose, you can modify the indexOf to make both strings lowercase first so the comparison doesn't fail with "foo" vs "FOO". Note also that if index exceeds the row's length, the entire row is returned (this can be changed to the first element (or whatever) easily by modifying the : row); portion.

Categories