Obtaining an array from a split string with negative values may be achieved by following these steps

I'm struggling to find the right approach here.

Can someone help me convert the number -800 into [-8, 0, 0]?

To start, I turned the number into a string and used the map function to create an array:

const number = -800;
const numberString = number.toString();
const arrayString = numberString.split('').map((x) => +x);

console.log(arrayString)

The current result is [ NaN, 8, 0, 0 ]

How can I change the NaN and first index of 8 to make it -8, while keeping the other indexes unchanged? This way, it will be [-8, 0, 0]

Any assistance would be greatly appreciated!

Thank you.

Answer №1

Consider using numberString.match(/-?\d/g) in place of split

let num = -900;
let stringNum = num.toString();
let newArr = stringNum.match(/-?\d/g).map(y => +y);

console.log(newArr)

Answer №2

To tackle this challenge, one approach is to perform the operation on the absolute value of the number and within the map function, verify if the original number was negative (specifically for the first index).

const number = -800;
const numberString = Math.abs(number).toString();
const arrayString = numberString.split``.map((x, i) => i == 0 && number < 0 ? -x : +x);

console.log(arrayString)

Answer №3

If you're unsure about regular expressions (Regex), you can utilize the Array.from method to convert a string into an array of numbers. Then, manipulate the first number based on the original number's sign.

console.log(convertNumberToArray(800));
console.log(convertNumberToArray(-800));

function convertNumberToArray(number){
  var result = Array.from(Math.abs(number).toString(), Number);
  result[0] *= number <= 0 ? -1 : 1;
  return result;
}

Answer №4

Implement a solution using the String#match method along with regular expressions to match an optional hyphen followed by the digit.

var num = -800;
var numStr = num.toString().match(/-?\d/g);
var numInt = [];

for (var j = 0; j < numStr.length; j++) {
    numInt.push(parseInt(numStr[j]));
}
console.log(numInt);

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

Slack Bolt API issue: Encounter a 'not_found' error while attempting to update modal view after submission

Recently, I encountered a challenge while working on my app. It involves a button that triggers a series of modals for user input. Everything works smoothly when updating and pushing new views, except when I try to update the current modal upon clicking th ...

Struggling to understand how to utilize REF, Arrays, and Methods? Let me

Hey there, I'm currently working on a lab for my C# class that involves ref parameters, arrays, and methods. Unfortunately, I've run into a few problems and am in need of some assistance. To simplify things, I've broken down the issues I&apo ...

Challenges when utilizing AJAX and JQuery for selecting multiple items and retrieving data from a JSON file

I am currently working on a live search feature that extracts data from a JSON file using AJAX and jQuery. The goal is to make the fetched value clickable and populate a multiselect field with it. Once this is achieved, the plan is to capture the remaining ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

The audio.play() HTML element fails to function in Chrome, preventing the audio from playing

I'm experiencing an issue with playing audio in Chrome when the audio.src is not called before the play call, but Firefox seems to handle it fine. Does anyone have any suggestions? You can check out the fiddle link below - http://jsfiddle.net/vn215r2 ...

Filtering data with React's multiselect checkboxes

I have created an amazing app that fetches a list of todos from this incredible source To enhance user experience, I developed a special CheckBoxDropDown component for selecting todo IDs Within the CheckBoxDropDown.js component, I am passing the onChange ...

What is the process for implementing Sequelize to manage and modify multiple tables simultaneously?

I am currently working on developing the back-end with DB using Sequelize ORM. My main challenge is creating or updating data in multiple tables simultaneously. Below are some examples of what I am trying to achieve: //Tables const main = sequelize.define ...

Show values in array that include a certain keyword

Currently, I am developing a search function for my json decoded results The code snippet that I have written is as follows: <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $va ...

Learn the process of extracting an array of objects by utilizing an interface

Working with an array of objects containing a large amount of data can be challenging. Here's an example dataset with multiple key-value pairs: [{ "id": 1, "name":"name1", age: 11, "skl": {"name": & ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

The process of ensuring an element is ready for interaction in Selenium with Javascript

I am currently working on creating an automated test for a Single Page Application built with VueJs. When I click on the registration button, a form is loaded onto the page with various elements. However, since the elements are loaded dynamically, they are ...

SolidJS seems to be behaving strangely by rendering content twice when incorporating routing

Just diving into SolidJS and came across an issue where my app seems to be rendering twice. I have a hunch that this has to do with how I'm handling routing. To demonstrate the problem, I've put together a simple example: app.tsx import { Suspen ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

What are the benefits of incorporating 'i in array' into my personalized 'array.indexOf' function?

I've come across code like this multiple times: function customArrayIndexOf(item, array){ for (var i = 0, l = array.length; i < l; i++) { if (i in array && array[i] === item) return i; } return -1; } But I'm unsur ...

Using Three.js to display a PerspectiveCamera with a visible bounding Sphere

My challenge is to create a Scene that loads a single .obj file where the object is fully visible in the PerspectiveCamera upon scene initialization. The field of view (FOV) is set at 60 The objects vary in size TrackballControls are utilized for camera ...

What is the process for attaching a dynamically generated object to the document's readiness event?

One of my tasks involves dynamically generating a slider element using the code snippet below: function NewDiv(){ for (var count=0; count < parseFloat(sessvars.storey_count); count++) { var string="<br><div ...

Show error messages from HTML 5 Validation using a software program

Is it possible to manually trigger the HTML 5 validation message using code? As far as I can tell, there isn't a straightforward way to do so directly. However, it seems we can prompt this message by simulating a click on the submit button. I attempt ...

Please wait for the window to finish formatting before attempting to print

I'm currently using the javascript code below to pass an element ID to a method. This method then formats that particular ID in a separate window and prints it. However, I've encountered an issue where the print dialogue box opens up before the w ...

Achieving Optimal Performance with Node.js Cluster in High-Traffic Production Settings

Currently, my web service is managing http requests to redirect users to specific URLs. The CPU is currently handling around 5 million hits per day, but I am looking to scale it up to handle over 20 million. However, I am hesitant about using the new Nod ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...