Unveiling the Evasive Final Element in a JavaScript Array

Having a Javascript array named full_range:

const range1 = _.range(1, 10, 0.5);
const range2 = _.range(10, 100, 5);
const range3 = _.range(100, 1000, 50);
const range4 = _.range(1000, 10000, 500);
const range5 = _.range(10000, 105000, 5000);
const full_range = range1.concat(range2).concat(range3).concat(range4).concat(range5);

A loop iterates over this array to fill another one.

var transY= [];
var transX= [];
for(let i = 0; i < full_range.length; i++){
    let y = getTrans(full_range[i], dampingFactor, natFreq); 
    transY.push(y);
    transX.push(parseFloat(full_range[i]));
    }

The outcome is passed to another function where:

console.log(transX); //Shows Array of length 91 (decimals at the end)
console.log(transY); //Displays Array of length 91
console.log("first");
console.log(transX[0]); //Correctly displays 1
console.log("Last"); 
console.log(transX[-1]); //Incorrectly shows "undefined instead of the last item

let xd = transX.pop();
console.log("xd:" + xd); //Works as expected by printing the last item in transX

The objective is plotting this data on a BokehJS graph, which behaves strangely with undefined values.

Why does "undefined" act like an array element when using slicing, but not with pop()?

How can I retrieve the array without any undefined elements?

Answer №1

In JavaScript, negative array indexing using bracket notation is not supported. However, you can achieve the same result by utilizing Array#at with negative indexes.

let arr = [1,2,3];
console.log(arr[-1]); // this is incorrect
console.log(arr.at(-1)); // retrieve the last element

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

What are the reasons behind lang sass not functioning within the style tag of a .vue file?

Even though I had previously installed sass-loader and node-sass in my project, I encountered an issue when attempting to use <style lang="sass"> in my vue file. The style did not compile as expected, however it worked perfectly without the lang="s ...

Mui CardContent not displaying transparent background color properly

I recently completed a course that used MUI v4, and I'm now facing challenges with transitioning to v5. Despite my best efforts, I am struggling to replicate all the styles and find myself stuck. This issue relates to my FeaturedMovie.jsx component i ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Displaying 'Undefined' instead of 'Cleared messages count' in the Clear Command

My goal is to display the number of deleted messages on an embed, but when the embed is sent, it shows bot deleted undefined messages. Here's a screenshot: https://i.sstatic.net/2GYxX.png I want it to show bot deleted ex: 15 messages. It works fine ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

When making a Post Request, the Req.body is found to be empty

Here is the code snippet from various files: In App.js file: app.use(express.json({limit:"30mb",extended:true})); app.use(express.urlencoded({extended:true})); In route.js file: router.route("/register").post(registerUser) Importin ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

Looking to customize session data for my online game within the same interface

I have successfully coded a game called Ninja Gold using PHP with CodeIgniter. The game works by setting session variables (Gold and Activities) when the index page loads if they are not set already. Each location clicked adds a certain amount of gold to t ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Customizing error messages in react-hook-form-mui: A step-by-step guide

I'm currently diving into the world of react-hook-form-mui library. The documentation provided for this project is quite brief, and I've been struggling to add a validation rule to my form field. Despite trying various methods, none seem to be ef ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

sent a data entry through ajax and performed validation using jquery

Is there a solution to validating the existence of an email value using ajax after validation work is completed? Despite attempting to check for the email value and display an alert if it exists, the form continues to submit regardless. See below for the ...

Issue: Route.get() is expecting a callback function, but instead received an undefined object in app.js

It's puzzling why this error is occurring. I have another model with a similar route and controllers, but it's not working as expected. The error message reads: Error: Route.get() requires a callback function but got a [object Undefined] at Route ...

Combining multiple Float32Arrays to create a single Float32Array

I need help creating a function that can flatten multiple Float32Arrays into one large Float32Array const first = new Float32Array([1,2]); const second = new Float32Array([3,4,5]); const third = new Float32Array([6,7,8,9]); const chunks = [ ...

What is the best way to update the background color for specific days in fullcalendar?

I have been working on my fullcalendar code and I am trying to figure out how to change the background color only for Feb 14. dayRender: function (date, cell) { var Xmas = new Date('2017-02-14'); var weekday = Xmas ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...