hey guys, can anyone explain this piece of code to me? - javascript

i'm currently learning JavaScript and have to do this challenge for one of the coding challenges and the challenge is :
"Create an object called 'scorers' which contains the name of the players who scored as properties and the number of goals as the value. in this game it will look like this:
{
Gnarby: 1,
Hummels: 1,
Lewandowski: 2
}"
the solution :
"loop over the array, and add the array elements as object properties,
and then increase the count as we encounter a new occurrence of a certain element"
the object :
const game = {
scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels']
};
the solution is :
const scorers = {};
for (const player of game.scored) {
scorers[player] ? scorers[player]++ : (scorers[player] = 1);
}
and the outcome is :
[Lewandowski: 2, Gnarby: 1, Hummels: 1]
i don't understand exactly what happens at the scorers[player] ? scorers[player]++ : (scorers[player] = 1);
what the scorers[player]++ do ?

It's a ternary operator that checks whether game contains the value of player as a property. If so, it increments the value of that property. Otherwise, it sets it to 1.
It can also be rewritten like so:
if(scorers[player]){
scorers[player]++;
} else {
scorers[player] = 1;
}
If scorers does not have the value of player as a property, scorers[player] will return undefined, which, when coerced to a boolean, is false.

Related

What does the syntax x:y mean in JavaScript?

I am following a course on blockchain which has the following piece of code.
What does " index:this.chain.length+1 " mean? Is index a variable in the object newBlock? Or is it a key value pair? If it is a variable, why don't we simply use index=this.chain.length+1? Also what is the type of the object newBlock?
function Blockchain()
{
this.chain=[];
this.newTranscations=[];
}
Blockchain.prototype.createNeBlock = function(nonce,previousBlockHash,hash)
{
const newBlock ={
index:this.chain.length+1,
timestamp:Date.now(),
// all of the transactions in this block will be the transactions that waiting to be put in a block
transactions:this.newTranscations,
// nonce is hust a number giving proof of the transaction
nonce:nonce,
hash:hash,
previousBlockHash: previousBlockHash
}
// As we move all the pending transactions to the new block, we clear this array
this.newTranscations=[];
this.chain.push(newBlock);
return newBlock;
}
var Box = {
"playdoh":{"playdoh":["none", "some", "none", "none", "some"]}
};
Box of playdoh upon playdoh, you're getting into the study of Objects/Arrays/Maps.
To call the above out, it'd be
console.log(Box["playdoh"]["playdoh"][0]);
= none
console.log(Box["playdoh"]["playdoh"][4]);
= some
console.log(Box["playdoh"]["playdoh"][5]);
= null (undefined)
is the same as
console.log(Box.playdoh.playdoh[0]);
= none
console.log(Box.playdoh.playdoh[4]);
= some
console.log(Box.playdoh.playdoh[5]);
= null (undefined)
It is one of several ways to initialize an object called newBlock in javascript. Take a look at this documentation on MDN
The index property is of type number in this case, and it is set to equal chain[].length + 1

React How to log different state elements in a loop

I'm trying to loop through 2 of the key value pairs in my state. They both have very similar names the only difference between them is that one ends in Day and the other ends in Night. Here is a simplified example of my project right now. My objective is for the log to come out with the results shown below:
state = {
energyType: "Electricity",
meterRate: "oneRate",
firstEnergyAmountDay: 1,
firstEnergyAmountNight: 2,
}
let days
if (this.state.energyType === "Electricity" && this.state.meterRate === "twoRate") {
days = ["Day", "Night"]
} else {
days = ["Day"]
}
days.map(day => {
console.log(this.state.firstEnergyAmount + day);
})
Right now my log just returns:
undefinedDay
undefinedNight
And I want the log to give me:
1
2
To do a computed property of an object, you need to use square brackets and a string
console.log(this.state["firstEnergyAmount" + day])
So that will concatenate strings together to produce either "firstEnergyAmountDay" or "firstEnergyAmountNight", and then the square brackets will look up the property with that key.

removing objects in an object in an array javascript

I've done some research on this issue. I am trying to manipulate an array of calculated values that looks like this in the console:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:Complex {re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
8:Complex { re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
This array is created dynamically through some math that I've come up with so there is no input data that I can give you. I'm trying to make the above array look like this:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:40.38334500994142
8:39.55961661806138
Using mathjs, I was able to evaluate my expressions and dynamically add the values into an array with the array.push command and display them. However, my code breaks once the imaginary values pop up in the results of my array.
How can I remove these imaginary numbers from my array? In other words, I need to remove the "im:" parts of the values when they begin to appear before I push them to the displayed array.
I tried to do this with some code I found from a previous answer to someone else's question (How do I remove a particular element from an array in JavaScript?) splice command like this:
var nodeVoltage2 = parser.eval(expression2);
//checks if there are imaginary values and removes them
if ("im" in nodeVoltage2) {
nodeVoltage2.splice(2,1)
}
//adds value to result array for analysis
nodeVoltages.push(nodeVoltage2);
but it returns in the console that "im is not defined".
Any help is greatly appreciated!
You can use the array map function.
Basically, we loop through the array. If the item has a .re property, we take that value only. If there is no .re property, we keep the value as is.
We can either write that in shorthand, as with result using the ternary operator and arrow function, or we can write it in a slightly more verbose but traditional way, as with resultTwo
let data = [
48
,47.71306060387108
,47.250273223993105
,46.59686907269243
,45.71876416434013
,44.53304242029258
,42.745236969423615
,{re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
,{ re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
]
let result = data.map((x) => x && x.re ? x.re : x);
let resultTwo = data.map(function(elem) {
// First, we need to check that the array element is not null / undefined
// We then need to check that it has a property called re that is also not null / undefined
if (elem != null && elem.re != null) {
// Just return the property we're interested in
return elem.re;
} else {
// Return the element as is
return elem;
}
});
console.log(result);
console.log(resultTwo);

Javascript ERROR, undefined, not an object

I am new in JavaScript, And I am trying to map my controller's buttons and leds for mixxx application. Is that an object, an array? var is missing.
BehringerCMDMM1.leds = [
// Master
{ "shiftButton" : 0x12 },
// Deck 1
{ "sync" : 0x30 },
// Deck 2
{ "sync" : 0x33 }
];
I have an error here,
BehringerCMDMM1.shiftButton = function (channel, control, value, status, group) {
// Note that there is no 'if (value)' here so this executes both when the shift button is pressed and when it is released.
// Therefore, BehringerCMDMM1.shift will only be true while the shift button is held down
var deck = BehringerCMDMM1.groupToDeck(group);
BehringerCMDMM1.shift = !BehringerCMDMM1.shift // '!' inverts the value of a boolean (true/false) variable
BehringerCMDMM1.setLED(BehringerCMDMM1.leds[deck]["shiftButton"], BehringerCMDMM1.shift);
}
about "shiftButton" as undefined.
also I have this function
BehringerCMDMM1.setLED = function(value, status) {
status = status ? 0x7F : 0x00;
midi.sendShortMsg(0x94, value, status);
}
This is from a javascript file I found on the internet created for a different controller. So, I am trying things to understand how can I configure mine.
BehringerCMDMM1.leds is an array of objects. Within that array, the element at index 0 is an object that has a shiftButton property. Thus, the only way to get the 0x12 value in your example is to do this:
BehringerCMDMM1.leds[0]['shiftButton']
So when this code executes...
var deck = BehringerCMDMM1.groupToDeck(group);
...the value of deck is probably something other than 0, and you're accessing one of the sync objects in the BehringerCMDMM1.leds array. For example, if the value of deck was 1, then this...
BehringerCMDMM1.leds[deck]['shiftButton']
...will be undefined because you're effectively doing this:
BehringerCMDMM1.leds[1]['shiftButton']
Ok,
I am new in JavaScript, And I am trying to map my controller's buttons and leds for mixxx application. Is that an object, an array?
You have a array of objects.
var is missing.
You should test what is inside yout deck variable. Try this:
console.log(deck);
if (deck in BehringerCMDMM1.leds) {
BehringerCMDMM1.setLED(BehringerCMDMM1.leds[deck]["shiftButton"], BehringerCMDMM1.shift);
} else {
console.log("Index: "+deck+" doesn't exist");
}

How should we have an interger like counter value in javascript map?

How can I create a value in java script map to behave like integer counter.
var map = { "cars" : count, "buses" : count };
The way I want to use this map is:
if (car) {
// incremeent the count of cars
} else {
// increment the count of busses
}
My question is how should such a map look like syntactically in javascript ?
You can initialize it like this:
var map = {cars: 0, buses: 0 };
Then, you can increment like this:
if (car) {
++map.cars;
} else {
++map.buses;
}
But, I suspect you need a little more logic to your if (car) so you can actually tell that it is a car type, not just a boolean but you haven't shown us how that part of your code works to know exactly what to suggest.
You could also be a little more object oriented and put the method on the map:
var map = {
cars: 0,
buses: 0,
count: function(obj) {
if (obj) {
++this.cars;
} else {
++this.buses;
}
}
};
map.count(item);
Again, you'll have to modify the if (obj) portion of this to actually discern whether the type is a car or not, but you haven't disclosed enough about your code to know how to do that.
var counts = { cars: 0, buses: 0 };
if (car) {
counts.cars++;
} else {
counts.buses++;
}
// or more succinctly:
counts[car ? 'cars' : 'buses']++;
If you have a parameter, say vehicles, whose value is either cars or buses, then you can do:
map[vehicles]++;
You can also do:
map[car? 'cars' : 'buses']++;
If you show more of what you are doing, more help can be provided on what is likely to be most appropriate.

Categories