I'm trying to get random number between 0 and Array.length.
I have this:
getRandom() {
const cars = Object.keys(this.index);
const randomInt = Math.floor(Math.random() * cars.length);
return cars[randomInt];
}
I ran this few times and found a 0 in one of the results from getRandom(). There is not key in my this.index object named 0.
Is my math function wrong?
UPDATE
After reading the comments, and I know the getRandom() is not wrong. I also have reset() function if you guys can look at it.
reset() {
const cars = Object.keys(this.index);
let i = cars.length;
while (i--) {
this.index[cars[i]] = 0;
}
}
Is it possible I'm adding a new key 0 at this.index object?
I can't see an actual problem here.
Object.keys will turn your named keys into numbers (look here https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), this numbers starts with 0.
So your function, as you wrote yourselv, will return an:
random number between 0 and Array.length
You can make use of this existing solution.
Generating random whole numbers in JavaScript in a specific range?
And pass 0 and array.length as params.
I wonder what you're seeing, but we're all lacking context here, so I made a little example to try the function to see the problem with my own eyes and it does not seem to have the problem you described.
Try it for yourself here - and maybe it's the data you're running the method on that is the problem?
Related
EDIT:
Apparently the lowest non-infinity value is -250.
I generated a silent audio file with DarkAudacity and the lowest frequency value I got was -249.21243286132812, which is BASICALLY -250
Oh yeah, the question title might be somewhat wrong, so I guess you should just do this, as an answer to the title's question:
for (let i = 0; i < FrequencyData.length; i++) {
FrequencyData[i] = FrequencyData[i] / 250 + 1;
}
Original Question:
What I want to have: An array of Frequency Data that is easier to work with.
What I need to do to achieve it: Abstract the Frequency Data into Values between 0 and 1. (0 being silent and 1 being "loudest")
The Problem: I don't know what the lowest value is that can be returned by AnalyserNode.getFloatFrequencyData() (However, I assume the highest value is just 0, unless I get told otherwise)
What I have tried:
Looking up the lowest possible value that can be returned. (everyone said -Infinity, which doesn't help because I would only get 0 or 1 if I tried to scale that)
Get the lowest value myself by console logging. (Kind of worked but I got -236.[lotsOfDecimalsHere], and I dislike to think that the lowest value has decimals)
Here is roughly what my second try was:
let lowest = Infinity;
function loop() {
myAnalyserNode.getFloatFrequencyData(myFrequencyData);
if (!myFrequencyData.includes(-Infinity)) {
lowest = Math.min(lowest, ...myFrequencyData);
}
console.log(lowest);
requestAnimationFrame(loop);
}
loop();
I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;
Okay, so I am pulling my hair out with this one. I am trying to make a function that will shuffle a virtual deck of cards. I saw examples online, but they were written in some syntax I am unfamiliar with. I really couldn't understand what was going on so I tried to write my own. Anyway, the way I am going about it, I am making a duplicate array and then randomly picking cards out of the first array and putting them into the second array one by one, then deleting the randomly selected card. Here's my code. The function is stopping once the length of the original array reaches 26.
shuffleDeck: function (deck) {
var newDeck = deck;
for (i = 0; i<newDeck.length;i++){
randomIndex = Math.floor(Math.random() * deck.length);
newDeck[i] = deck[randomIndex];
deck.splice(randomIndex,1);
console.log(deck.length);
}
return newDeck;
}
Arrays are passed by reference in JavaScript so the splice is removing from the array which is why it stops
See
http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/
You can do
var newDeck = deck.slice(0);
For a copy
i am having issues (very lost) in making a code that me and my friend were given to create.
So I am suppose to compute and return the average of all values in a given array named customerBalance, the array holds the amount of "what customers owe my business" (I dont own a business) and each item in the array holds the "customers balance", i also have to use a for() to process the array and calculate the average and divide by customerBalance length, and finally return the average.
Here is my code so far
function average() {
customerBalance
for(i=0,i++)
sum(customerBalance)
total=sum/5
return average;
I know that this is COMPLETELY wrong, I am not sure on how i start typing the array, please don't be harsh I would really like to know how to do this.
Thank you and have a great day
function average(customerBalance) {
if (customerBalance.length == 0) { // Prevent division by zero later
return 0;
}
var total = 0;
for (var i = 0; i < customerBalance.length; i++) {
total += customerBalance[i];
}
var average = total/customerBalance.length;
return average;
}
You have many problems:
The parameter to a function goes in the parenthese after the function name, not the next line.
Your for() syntax is all wrong. You need to put the initialization, repetition test, and increment separated by semicolons.
There's no sum() function in Javascript. And even if there were, you would need to assign the result to a variable.
When you calculate the average, you're putting it in total, but then you're returning average, which is the variable that contains the function, not the average you calculated.
Other recommendations:
Don't hard-code the array size, use array.length to get it.
Always put braces around the body of for, if, while, etc. even if they're just one line.
Local variables should be declared with var.
I want to know if it is possible to make a number the opposite to what it currently is using JavaScript. ie if a number is 400. Is it possible to make it -400, similar if a number is -400 is it possible to make it 400?
This is not jQuery!
Just multiply it by -1.
num = "400"
console.log(-num);
Core JS,
function opposite(number) {
return(-number);
}
As the shorter solution from http://www.codewars.com/
In one Line..
const opposite = number => -number;
function opposite(number) {
let result;
if (!isNaN(Math.sign(number))) {
result = number * (-1);
}
return result;
}
const opposite(num) {
return num * -1;
}
What I also realized was that if you just:
const opposite(num) {
return -num;
}
The negative can be used to create a positive when returning the num because if it is a negative integer turning into a negative number the two negatives cancel each other out into a positive.
To shorten the code you can also use:
const opposite = num => -num;
All ways work. It's all in how fast you want the solution. The faster the better. The most simple way a code can be written the better.
I really liked #KRESH 's answer because it made me find out what Math.sign() was. The whole adventure of figuring out what his code did was fantastic. I wonder what it could be best used for. That's what's going to be fun figuring out next.