Trying to make a visualizer, the values in fft.getEnergy() (a p5.js sound library function) returns the amount of volume at each frequency. I would like to take the first 1024 of these volumes and store them in an array so I can map each number to a graph. The problem is when I try to add them to the array, the array stores only 1 value 1024 times and not the first 1024 different values.
This is a snapshot of the getEnergy() values: https://imgur.com/a/7zSV9DK
And this is a snapshot of the array I'm trying to make while trying to push the first 1024 values: https://imgur.com/a/cs3FA0U which shows that it's printing one value 1024 times.
var arrays = []
for(var i = 0; i < 1024; i++)
{
arrays.push(energy) //energy = fft.getEnergy("bass")
}
console.log(arrays)
From what I read on this page https://p5js.org/reference/#/p5.FFT/getEnergy
getEnergy("bass") return a "predefined frequency ranges" which I guess is an array of energies of predefined frequencies from 0 to bass max limit.
What you do in your for loop is pushing the result array of frequencies to your result array 1024 times (an not 1024 individual values as you want).
so what your are trying to do is
const resultArray = [];
for (let i=0; i<1024; i++) {
resultArray.push(energy[i]);
}
console.log(resultArray);
(note that I don't use var. I Suggest that you look at the difference between var | let | const and that you learn about the notion of scope too.)
Yet this code above is not quite good either. I suggest you look at what the Array object in JS is and look at all the ways to manipulate it. Using the slice method would be better. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
const resultArray = energy.slice(1024);
And then to sort your array you can use the sort method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
(Though be careful that "the default sort order is ascending, built upon converting the elements into strings")