Why does the console print "undefined" when I print index 3? I'm trying to set index 3 to false and after 7 secs set it to true.
I've tried to change "nr", index 2, with success trying to narrow down the problem.
if (Math.random() < 0.005) {
nx = Math.random()*1000; //index0
ny = 200; //index1
nr = 5;//index2
var nfall = false; //index3
Apples.push([nx,ny,nr,nfall]); //simply inserting 'false' into index 3 doesn't work either.
setTimeout(function(){ Apples[2][2] = 500; Apples[2][3] = true;}, 7000); //3rd apple
console.log("New circle, x:"+Apples[2][0]+" y:"+Apples[2][1]+" nr:"+Apples[2][2] +" nfall:"+Apples[2[3]]);
//What works - in 7 seconds "nr" is updated from 5 to 500, but nfall is still undefined and NOT = true
Initially I expect the output of false from index 3 "nfall" then I expect the output of true from index 3 "nfall" after 7 secs.
Thank you
In your console.log call, you're accessing the array like this:
Apples[2[3]]
But it should be
Apples[2][3]
In the first version, you're accessing index 3 of the number 2 which actually is not an error, just undefined.
Your issue is the last part - you're accessing Apples[2[3]] which doesn't exist, and it's invalid syntax. You want to get the third item in Apples (which is an array), then access the fourth item of that array - do it simply with `Apples[2][3]:
const Apples = [1, 2, [3, 4, 5, 6]];
console.log(Apples[2][3]);
Related
I'm trying to sort data from API for chart, so I need to filter it based on currency name so I can get their rates.
Algo is working properly but I'm getting weird output in my browser and chart also.
Output from tempRates in browser looks like this: [7.4429, 7.4429, 7.4392, 7.4392] which is the correct output.
But when I expand the same array in the browser console I get this output:
(4)[7.4429, 7.4429, 7.4392, 7.4392]
0: 1
1: 1
2: 1
3: 1
And that goes for all arrays.
But value of last array is (4)[1, 1, 1, 1] and that is the expected output.
Object.keys(data.rates).forEach((key) => {
this.data.labels.push(key); // date
});
Object.values(data.rates).forEach((value) => {
tempCurrency = Object.keys(value)[i];
Object.values(data.rates).forEach((rate) => {
if (tempCurrency === Object.keys(rate)[i]) {
tempRates.push(rate[tempCurrency]);
//tempRates.push(Math.round(Math.random() * 100));
}
});
console.log("log before push", tempRates);
this.data.datasets.push({
label: tempCurrency,
data: tempRates,
});
i++;
if (!(i === Object.keys(data.rates).length)) {
tempRates.length = 0;
}
});
I also have tried with random numbers and the output still has the same problem. All arrays have the value of last array.
Console screen shoot
All I had to do was change the tempRates.length = 0; to tampRates = [].
I just don't know what is the difference between those two solutions. I would be grateful if someone could explain it to me.
I'm trying to solve a problem I have in my JS which is related to the following snippet
const signatureOrder = role => {
let order;
switch (role) {
case 'GUARDIAN':
order = 2;
break;
case 'ASSENTEE':
order = 3;
break;
case 'COUNTERSIGNEE':
order = 4;
break;
default:
order = 1;
break;
}
return order;
};
This method basically takes a role which currently is 4: CONSENTEE, GUARDIAN, ASSENTEE, COUNTERSIGNEE.
The CONSENTEE is always 1 and the order is always as the numbers from 1 to 5.
However, there can be a situation where I can have like multi roles coming:
1 consented
2 guardians
2 assentee
1 countersignee
This will be translated by the method in the following order
1 consented
2 Guardian
2 Guardian
3 Assentee
3 Assentee
4 Countersignee
This is not very correct and the output should be an increment of the single values but keeping the order fixed as below:
1 Consented
2 Guardian
3 Guardian
4 Assentee
5 Assentee
6 Countersignee
so what happens is that if we have already a guardian the next guardian becomes the previous guardian + 1 but stays always after Consentee and before Assentee.
The scenarios areas:
consentee is the one always be there is always 1
Always we have 4 roles
but we can have different combinations like no guardians, no assentee, yes countersigned and so on
The always present role is consentee the other roles are present or not depending of the situation
We can have already a list of this roles and adding again guardian should change the values for example
we have C 1, G 2, A 3 and we add G so will change +1 everywhere so will have
c1, G 2, G 3, A 4 ...
I would like to understand how to solve this in the right manner.
It seems to me you need something like this:
const sortRoles = rolesArray => {
const orderOfRole = {
'CONSENTED': 1,
'GUARDIAN': 2,
'ASSENTEE': 3,
'COUNTERSIGNEE': 4
}
rolesArray.sort((role1, role2) => orderOfRole[role1] - orderOfRole[role2])
}
where, in the end, the order is just the index in the sorted array, incremented by 1:
roles = ['GUARDIAN', 'ASSENTEE', 'ASSENTEE', 'CONSENTED']
sortRoles(roles)
roles.map((role, index) => console.log(`${index + 1}: ${role}`))
// 1: CONSENTED
// 2: GUARDIAN
// 3: ASSENTEE
// 4: ASSENTEE
You can extend this to having an object for the role, instead of a string. In that case you just need to extract the string from the object in the comparison function of sort() and use it like above.
You can sort all your elements based on an orderArray. Then, assign the order based on the element index.
Based on this answer:
const orderArray = ['CONSENTEE', 'GUARDIAN', 'ASSENTEE', 'COUNTERSIGNEE']
const elements = ['CONSENTEE', 'ASSENTEE', 'GUARDIAN', 'COUNTERSIGNEE', 'ASSENTEE', 'GUARDIAN']
elements.sort(function(a, b){
return orderArray.indexOf(a) - orderArray.indexOf(b);
});
const withOrder = elements.map((el, i) => {
return {role: el, order: i+1}
})
console.log(withOrder)
Hey guys this is my first post on here so take it easy on me! Apologies in advance for how basic this question is as I'm a beginner. I'm in the process of self learning and googling has been my best friend so far but I'm struggling to work out what's going wrong here. Maybe it is my approach altogether...
I am building a very simple game of Yahtzee with Javascript as my first project. Most of the program works smoothly however I can't seem to get the logic right for a full house. For anyone that doesn't know Yahtzee is played with 5 dice and a full house is a pair combined with 3 of a kind so for example [1, 1, 1, 6, 6] or [4, 4, 5, 5, 5]. I have a generated array with .sort() applied so my thinking is the logic should be if index 0 = index 2 and index 3 = index 4 OR index 0 = index 1 and index 2 = index 4. I have tried with multiple nested if statements and without nested parentheses but no luck there either. I understand it must be how I've used the logical operator as the first parentheses of code in each if statement works by itself.
function fullHouseFunc() {
if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
} else if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
}
};
You were almost there, just change the indices in the first if statement to 0 === 1 and 2 === 4. You had both statements checking 0 === 2 and 3 === 4:
let fullHouse = document.querySelector('.fh')
let newRoll = [4,4,5,5,5]
function fullHouseFunc() {
if ((newRoll[0] === newRoll[1])&&(newRoll[2] === newRoll[4])) {
fullHouse.innerHTML = 25;
} else if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
}
}
fullHouseFunc()
<div class='fh'></div>
param.FilterExpression = "#black_listed = :black_listed_val";
param.Limit = 5
param.ExpressionAttributeValues = {":black_listed_val": body.blacklisted};
param.ExpressionAttributeNames = {"#black_listed": "black_listed"}
param.ScanIndexForward = true
param.ExclusiveStartKey = {"id": "11931258-b582-4d2d-98d9-aa8ae0fe2e43"}
I can do forward pagination with this code, but how could I go back?
To page backward you need to set ScanIndexForward to false AND the ExclusiveStartKey to the key of the first item of the second page. As an example, say your first page is items 1, 2 & 3. The response from that will include a LastEvaluatedKey for 3. You can use that to go forward by passing that to the ExclusiveStartKey, resulting in 4, 5 & 6. Going backward you can't do that, because using that same key would result in just 2 & 1. Instead you need to use the key of 4 as your ExclusiveStartKey.
Change
param.ScanIndexForward = true
to
param.ScanIndexForward = false
I have a quick question regarding the deletion of a node in the center of a linked list given that you only have access to that node. I've taken a look at the solution and while I understand what is happening, I am confused as to what actually happens to the node. For instance, if I have the nodes with values 1, 2, 3, 4, 5 in my linked list, why am I left with 1, 2, 4, 5 instead of 1, 2, 4, 4, 5?
Thanks in advance for any help.
SinglyList.prototype.deleteMiddle = function(value) {
var current = this.head;
while (current.value !== value) {
current = current.next;
}
if (current.next) {
current.value = current.next.value;
current.next = current.next.next;
} else {
current = null;
}
}
So you have linked list with nodes 1, 2, 3, 4 and 5, from which node 3 is removed. The removal of node 3 is actually a redirecting of some links. In this case, node 2 will not link to node 3 as its next node anymore, but it will link to node 4 as its next node instead. In case of a doubly linked list, this is also true the other way around, e.g. node 4 will link back to node 2 instead of node 3.
So, node 3 will not actually be removed physically, but any references to node 3 will be removed, which means logically it does not exist anymore. At some point in time, a garbage collector will remove node 3 physically because there are no more references pointing to that node.
Basically, you need another variable for the last node.
If not at the start, then combine the previous next pointer to the actual next pointer:
lastNode.next = node.next;
Working model:
function Node(value) {
this.value = value;
this.next = undefined;
}
function setValues(a) {
var n = new Node(a.shift());
if (a.length) {
n.next = setValues(a);
}
return n;
}
function deleteNode(list, value) {
var node = list,
lastNode;
while (node.value !== value) { // find value
lastNode = node;
node = node.next;
}
if (lastNode) { // inside the list
lastNode.next = node.next;
} else { // at the start
list.value = node.next.value;
list.next = node.next.next;
}
}
var list1 = setValues([1, 2, 3, 4, 5]);
document.write('<pre>' + JSON.stringify(list1, 0, 4) + '</pre>');
deleteNode(list1, 3);
document.write('<pre>' + JSON.stringify(list1, 0, 4) + '</pre>');
I'm not sure how this relates to JavaScript but you can think of a Linked List as a series of nodes:
1 -> 2 -> 3 -> 4 -> 5
Each node has a pointer to the next node. When you remove 3, the pointer from on 2 to 3 is updated to point to what 3 pointed to (4). So you end up with:
1 -> 2 -> 4 -> 5
If you are asking how do you delete it if you can't go backwards to see that 2 is pointing to 3, well think about how you traverse a linked list -- there is only one way to go. So an algorithm to remove a node is going to have to keep a pointer to the prior, current and next node. That way, when the current node is remove (3), it can look at the prior (2) and the next (4). Of course 3 already has a reference to 4 so the next pointer isn't needed.
There's more than one linked list implementation out there. But if we're talking abstract: if you remove one element in a linked list, it becomes two linked lists. one ending before the removed element, the second one beginning after the removed element.
What happens to the node ist what you actually mean by "deleting". There is no "emtpy" space in the linked list where the removed node once was. It was removed, as requested. Depending on the implementation of the remove operation the lose ends of the two resulting lists can be combined, to form a (one!) new linked list, with 1,2,4,5. Or they are not, then you end up with described 2 lists. The end of list 1 points to nil / null / somwhere, the reference to the beginning of the other list is lost, unless you saved it somewhere.
So you end up with either 1->2->4->5 or 1->2-> + 4->5