How can you identify a sign change in a JavaScript array?

I'm working with a JavaScript array and need some help. The array looks something like this:

var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4...];
var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4...];

My goal is to create a function that can detect sign changes in the array and return the position along with the numbers involved in the change. So, the output should look like ['index','num1','num2'] as shown in the example below.

function getSignChange(exampleArr1){
 ...
 return someArray;
}

The expected output should be:

[
  [2,1,-2],  //index = 2 change from 1 to -2
  [5,-7,5],  //index = 5 change from -7 to 5
  [8,2,-3],  //index = 8 change from 2 to -3
]

If anyone has any advice or guidance on how to achieve this, it would be greatly appreciated. Thank you!

Answer №1

Perhaps this solution can guide you:

var dataArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4];
var dataArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4];

function findSignChange(arr){
 let positive = arr[0] >= 0;
 return arr.map((element, index) => {
  if (positive && element < 0 || !positive && element >= 0) {
    positive = arr[index] >= 0
    return [index-1, arr[index-1], element]
  }  
 }).filter(x => x != null);
}

console.log(findSignChange(dataArr1));
console.log(findSignChange(dataArr2));

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

Adding Hash to Array: final Hash replaces existing array elements

Here is a Ruby script I am working with: arr = ['bob', 'jack', 'smith'] array_of_hashes = Array.new hash = Hash.new arr.each do |item| hash.clear hash[:name] = item array_of_hashes << hash end puts array_of_hash ...

Implementing JavaScript from dojo.xhrGet within a Symfony framework

Hey there! I'm diving into the world of dojo and symfony, but I've hit a snag. I'm trying to do an Ajax reload of a section on my page, but it involves executing a JavaScript function. While I've got this down in prototype and jQuery, I ...

Improving an HTML list with JavaScript

My current project involves a JavaScript game similar to Scrabble. I want users to be able to create new words in the game, and have those words added to a list that is displayed on the page within a div element. However, I'm struggling to understand ...

Tips on displaying five bootstrap modal popups simultaneously on a webpage

I'm looking to achieve a specific functionality that involves opening multiple bootstrap modal popups on one page simultaneously without overlapping each other. Specifically, I need a button to trigger the opening of five separate modals each containi ...

Only when the tab is refreshed will React Query be shown

I'm facing a tricky situation and can't seem to find a solution through Google search. My current challenge involves using the React Query library with TSX to display fetched data in a simple list. However, the data is only fetched and displayed ...

Ways to prevent users from selecting dates that are over a year from the present date in a datetime-local TextField

I am currently working on a feature to disable dates that are in the past and more than 1 year from the current date. While I have successfully managed to disable past days, I am facing difficulties in disabling dates that are further than 1 year into the ...

The React Reducer is yielding an undefined result

I am facing an issue with a particular property, disableselectors, which is currently returning undefined in my mapStateToProps(state). return { token: state.token, url: state.url, disableselectors: state.disableselectors } Here is the reduce ...

How can one determine the completion of a chunked download request in Angular's HTTP client?

Currently, I am utilizing angular's HttpClient to retrieve an arraybuffer. The server is transmitting the data along with the following headers: *To avoid any confusion, the download route essentially retrieves a chunk file stored in the cloud. Howev ...

Issue with gulp-uglifyjs arising from an empty return by gulp.src

Within a directory named app, I am iterating through an unknown number of folders to generate a folderName.min.js file for each one. Below is the Gulp script being used: var es = require('event-stream'); var uglify = require('gulp-uglifyjs ...

What is the best way to ensure that the input submit element is only visible after the input checkbox element has been checked?

For a school project, I am attempting to create a simulated reCAPTCHA box. Although my code is complete, I would like the functionality to submit your response from the input fields above only after selecting the reCAPTCHA checkbox. Upon researching, it ap ...

Can node.js be used to extract slides from PowerPoint and convert them into images?

We are currently in the process of creating a new application that utilizes sailsjs (node + mongo) as its backend system. Our client has requested a specific feature where users can upload *.ppt files and potentially extract all slides to save them as ima ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Navigating the Path: Strategies for Caching Server-side Rendering in Next Js

I recently developed a Next JS Project along with a REST API implemented in PHP. My website is heavily reliant on API requests, which has prompted me to consider caching certain data points. I want to minimize the frequency of API requests for improved ef ...

How can I remove a row from a JavaScript array based on the value of the first item in the row?

Creating an array in JavaScript can be done like this: var myArray = new Array(); myArray.push({ url: urlValue, filename: fileNameValue }); As time goes on, the array will accumulate various items. If you need to delete a specific row based on the urlVal ...

The width of Material UI Grid decreases every time it is re-rendered

I'm attempting to display a list of 25 words in a 5x5 grid using the MUI Grid component. The grid is structured as a <Grid container direction="column"> with five <Grid item> elements. Each <Grid item> contains: <Grid co ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

The middleware attached to the router using router.use is not being executed

My NodeJS server application is up and running smoothly, thanks to the implementation of route protection I learned from an informative tutorial. After successfully obtaining a working token for login purposes, I decided to apply a middleware that would se ...

Enhancing wordpress custom fields using ajax without overwriting them

Seeking assistance with updating a custom field in WordPress. I have a gallery of images with textareas for comments attached to each image. Currently, I can enter text into a textarea and save it instantly using AJAX to the database. However, when I add a ...

Steps for recreating a Jquery Mobile form element with the same name after destroying it

As I delve into Jquery Mobile, I encounter a scenario where I must dynamically generate form fields (select, input, etc) using the following approach: $fieldInput = $('<input type="text" name="' + fieldName + '" />'); Initially, ...

Place the image on the canvas

I currently have a canvas where I am able to add text layers and images from flickr. My goal is to enable users to upload an image to the canvas using the html input. For uploading images from flickr, I am using this code: $(".search form.image-search"). ...