Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr.

const newArr = [1,3,5,8,9,3,7,13]
const zeroArr = Array.from(Array(newArr.length), () => 0);
console.log(zeroArr) // [0,0,0,0,0,0,0,0]

Now, the goal is to change the value at the last index of zeroArr from 0 to 10, so it should end up like this:

const result = [0,0,0,0,0,0,0,10]

How can I achieve this modification?

Answer №1

To update the final element in an array, you can use this method:

result[result.length-1] = 10;

Check out this Stack Snippets demonstration

const newArr = [1,3,5,8,9,3,7,13];
const zeroArr = Array.from(Array(newArr.length), () => 0); 
let result = zeroArr.slice(); // Create a duplicate
result[result.length-1] = 10;

console.log(result);

Answer №2

To achieve this, you can utilize the Array#map method and evaluate if it is the last element in the array to return 10; otherwise, return zero.

var numbers = [2, 4, 6, 9, 12, 5, 8, 14],
    result = numbers.map((value, index, arr) => 10 * (index + 1 === arr.length));
    
console.log(result);

Answer №3

Here is an alternate approach:

let numbers = [2,5,8,12,3];
let multipliedNumbers = numbers.map(num => num * 2);
console.log(numbers); // [2, 5, 8, 12, 3]
console.log(multipliedNumbers); // [4, 10, 16, 24, 6]

Answer №4

Firstly, transfer the data from array newArr to another array called zeroArr. Next, insert the number 10 into a specific position in the ZeroArr using the push method. Finally, display the contents of the 'ZeroArr' by printing them out.

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

The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data. The code I have successfully creates the map, reads in the data, and when I use cons ...

Is there a way to transfer JavaScript data to PHP?

<div> <p>This is a sample HTML code with JavaScript for tallying radio button values and passing them to PHP via email.</p> </div> If you need help converting JavaScript data to PHP and sending it via email, there are v ...

Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my ...

Show a single jQuery Validation error

I am struggling with displaying an error message at the top if validation fails, without using the errorPlacement option. Instead, I want to showcase the message in a Bootstrap alert box. Below is the HTML code snippet: <form method="POST" action="/ro ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

What is the process for obtaining a JSON result after completing an upload?

I recently started working with the razor view engine and I have encountered a situation where I need to upload an image using the Change event of an image browser. The jQuery function for this task is as follows: $("#billUpload").change(function (){ ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

Is there a way to execute a function after EACH user interaction?

I am in the process of developing a React Native kiosk application for an Android tablet that will be mounted on a wall. The main requirement is to include a "screen saver" feature, where if the user does not interact with the screen for 30 seconds, it wil ...

Tips on removing authentication token when logging out in react native

Working with the Django Rest Framework and React Native for the front-end, I am currently facing an issue where the authentication token persists even after a user logs out from the front-end. This is evident as the token still shows in the Django admin pa ...

Are foreign characters the culprit behind the JSON parsing problem?

I am encountering an issue while attempting to parse a field containing JSON data returned from an API. The data includes various unusual characters like East Asian symbols and curly quotes, causing this error to appear. I am unsure of how to resolve it - ...

Organizing data in an array of structs

I am facing an issue with retrieving and storing songs and lyrics from a sqlite database into an array. The array structure is defined as follows: struct KArray { let SongTitle: String let SongLyrics: String let ESongTitle: String func ma ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

I am currently implementing a unique scrollbar component to enhance the user experience within my list of options displayed in the MUI Autocomplete feature

Seeking a way to integrate a custom scroll feature from this npm package into the list of options for Material UI autocomplete. Consistency is key in my application, and the default scroll appearance on mui autocomplete doesn't quite align with the re ...

How can I use a dropdown with checkbox to toggle the visibility of a specific div in React?

I have come across a relevant question, but I am struggling to apply it to multiple divs. I haven't found a solution that quite fits my needs. Show or hide element in React Currently, I am using the dropdown with checkboxes from MUI. I am seeking a ...

The pause button will still function, even if the scrolling feature is enabled

I've successfully implemented a feature that pauses and plays the video on scroll when it reaches a certain pixel height. However, I'm facing an issue where the code automatically plays the video whenever the scroll position is more than 13500px ...

Discover the secret to incorporating concealed text in WordPress with a hidden div through the power of JavaScript

For a while now, I've been trying to implement a functionality where clicking on a text reveals a dropdown menu with more information, similar to a "read more" feature. I have limited experience in Java or jQuery, and I can't figure out if the i ...

Setting default values for JSON objects by analyzing the data of other objects within the array

I've been grappling with this issue for about 6 days now, so please bear with me if my explanation is a bit convoluted. I'm using NVD3 to showcase graphs based on data retrieved from BigQuery. While the data and graph setup are correct, the probl ...

Incorporating Products from an Iframe into the Cart on Woocommerce

I recently set up a store using WooCommerce, and I have a unique situation where my customizable products are displayed within an iframe. The "add to cart" button is also contained in this iframe. Whenever I click on the Add to Cart button, I receive a mes ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

VueJS 3 - Issue with applying the <router-link-active> class to routes that share the same path starting name

In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active> class. Everything works as exp ...