Is it possible to transform all values in arrays to 0s in JavaScript/p5.js during the copying process?

I’m struggling with a simple code where I want to store an array of arrays containing FFT audio data. It seems like there might be a JavaScript issue because when I try to push the array into another array called spectrums, all the values inside spectrums turn out to be 0s instead of their actual values. I am using array.splice(0) for what’s supposed to be a deep copy. Can anyone spot what I’m doing wrong here?

var fft,mic;

function setup(){
  var myCanvas = createCanvas(800,800); 
  fft = new p5.FFT();
  ellipse(400,400,50,50)
  colorMode(HSB,100)
  spectrums=[]
  mic = new p5.AudioIn();
  mic.start();
  fft = new p5.FFT();
  fft.setInput(mic);
}

function draw() {
  background(255)
  s = fft.analyze(16)
 for(si=0;si<s.length;si++){
   fill(s[si]%100,100,100)
  rect(si*10,0,si*10,s[si]) 
 }
 spectrums.push(s.splice(0))
  if(spectrums.length > 5){
    spectrums.splice(-1,1)
  }
  console.log(spectrums[0][0]) //this prints 0 always
for(si=0;si<spectrums[0].length;si++){
   fill(spectrums[0][si]%100,100,100)
  rect(si*10,400,si*10,spectrums[0][si]) 
 }
}

Answer №1

When working with arrays in JavaScript, it's important to differentiate between slice() and splice()

If you use:

spectrums.push(s.splice(0))

The array s will be emptied starting from index 0.

Instead, you should use:

spectrums.push(s.slice(0))

slice() creates a copy of the original array without modifying it.

On the other hand, splice() alters the original array by adding or removing elements.

Answer №2

I take full responsibility for the issue. I mistakenly used unshift instead of pop. The initial array received contains only 0s. You can view my intended outcome here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for managing asynchronous forEach loops, inserting outcomes into a database, and displaying the finalized dataset

I want to achieve the following steps: Call an API resource Receive an array of records - [arr] Iterate over [arr] and execute a function which involves making another async call to an API for each item Create an object for each iteration that includes el ...

Python: How to determine if a specific part of an element is present in an array?

I have a list as shown below: ['MLPClassifier-81991331-57fe-40f8-86b2-fa570e8a9010', 'RandomForestClassifier-fbf96287-c16b-4e1e-ba10-66d5747742c7', 'KNeighborsClassifier-34f6b483-618f-407a-88bb-902972db40db'] If I define mod ...

Looking for ways to detect memory leaks in your JavaScript application using Selenium?

While utilizing Java and Selenium for automated testing of a JavaScript web application, the issue of memory leaks has arisen. I am interested in ways to effectively test for them. Is there a simple method to obtain memory usage and other profiling data fo ...

Discovering when the DOM has finished rendering in AngularJS with ng-repeat

I am looking for a way to trigger an alert or message upon completion of rendering in my HTML DOM using AngularJS, specifically when dealing with multiple ng-repeats. HTML Code: <body> <div ng-controller="Ctrl"> <div ng-repeat= ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

Finding the Nearest Value in an Array

My code involves a changing total number that I need to match with the closest value in an array of numbers, returning the index of the matching person, which should be Mia Vobos. I am attempting to find two people whose scores add up to the same total or ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

What is the best way to execute a function in JavaScript and have it return the output as an image

I have created a special function that selects the image source based on a given criterion: function facilityImg(arr, x) { switch (arr[x]) { case 'Yes': return "Images/checked.png"; case 'No': ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Setting a Javascript value to a Controller variable within an ASP.NET MVC View

I am trying to set the javascript variable contentArea to match content.Contents in my controller. How can this be accomplished? <script language="javascript" type="text/javascript"> $("#btnTest").click(function () { var content ...

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

Access-Control-Allow-Origin does not permit AngularJS Origin http://localhost:8080

I'm working on a web application using AngularJS. It's an admin interface that depends on a json-rpc API hosted on a different domain. When testing in my local environment, I encountered the error "Origin http://localhost:8080 is not allowed by ...

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...

Is there a way to minimize the use of .value in Vue 3?

After recently diving into Vue 3, I find myself struggling to grasp some key concepts of the composition API. My current challenge involves converting a library from Vue 2 to Vue 3, where a reactive property named layout is being passed down to child compo ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

The function createReadStream completes execution without resolving

Currently, I am in the process of developing a program that is aimed at iterating through files within a specified directory in a Linux environment. I have implemented a custom function called "myReadFile" which returns a new promise, and it is expected ...

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...