attempting to separate negative and positive values using JavaScript

I'm a beginner and looking to create a function that can filter out negative, positive, and zero values in an array. Although I have managed to achieve this using a for loop with hardcoded numbers, I am struggling to convert it into a reusable function. Can someone please assist me with this?

var arr=[1,3,5,-9,-3,0];
var new_arr = [];
var new_arr2 = [];
var new_arr3=[];
for(i =0; i < arr.length; i++){
    if(arr[i]>0){
      new_arr.push(arr[i]);
    }
    else if(arr[i]<0){
      new_arr2.push(arr[i]);
    }
    else if(arr[i]===0){
      new_arr3.push(arr[i]);
    }  
}
console.log(new_arr3.length/arr.length);
console.log(new_arr2.length/arr.length);
console.log(new_arr.length/arr.length);

Answer №1

How about trying out something like the following?

def sorting(arr):
  postive = []
  negative = []
  zero = []
  for i in arr:
    if i > 0:
      postive.append(i)
    elif i < 0:
      negative.append(i)
    else:
      zero.append(i)
  print(len(zero) / len(arr))
  print(len(negative) / len(arr))
  print(len(postive) / len(arr)

sorting([9, -2, -7, 0, 3, 0]);

This updated function accepts an array as an input, making it simple to execute by passing the array as a parameter.

Answer №2

Another approach you can consider is by treating 0 as a positive number. Feel free to customize the conditions based on your needs.

 function sortPositiveNegative(array ){

    positive = array.filter(function (a) { return a >= 0; });
    negative = array.filter(function (a) { return a < 0; });
    return [positive, negative];

  }

var array = [2,4,6,-8,-4,0];
console.log(sortPositiveNegative(array));

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

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

Using v-model in Vue, the first option has been chosen

Is there a way to set a default value for myselect when a user visits the site for the first time? I want the first option to be selected initially, but allow the user to change their choice if they prefer another option. Can this be achieved using v-model ...

What is the preferred workflow for client-side modules: (Browserify + npm + gulp) or (RequireJS + Bower + gulp)?

As I delve into various client-side Javascript modules workflows for my current Node.JS Express project, I find myself torn between Browserify + npm + gulp and RequireJS + Bower + gulp. While I lean towards CommonJS due to its syntax, the idea of sharing ...

Issue with JQuery image upload functionality not functioning correctly for upcoming events

In order to enable users to upload images with their posts, I have implemented an upload form alongside every reply form. Users can upload an image by clicking the upload button and then submitting the post. Currently, the upload form works for the first ...

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

How can we effectively manage error responses and retry a failed call in NodeJS without getting tangled in callback hell?

I am in search of an effective approach to handle the given situation. I am curious if employing promises would be a helpful solution? Situation Overview: When a call retrieves a callback, and this callback receives an error object as a parameter. My obj ...

Managing email delivery and responses within Nextjs server functions using Nodemailer and React Email package

Currently, I'm working on a Next.js project that involves sending emails. The functionality works as expected, but I've encountered an issue when trying to verify if the email was successfully sent or not. Here's my current setup: await tran ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

Can Node.js Utilize AJAX, and if So, How?

Coming from a background in browser-based JavaScript, I am looking to dive into learning about node.js. From my current understanding, node.js utilizes the V8 engine as its foundation and offers server-side JavaScript capabilities along with pre-installed ...

iOS Safari does not support the forEach method

I am facing an issue with my function that loads specific modules on specific pages based on body classes. Strangely, the forEach function is not working on iOS devices, particularly in Safari. I have been trying to troubleshoot this problem for some time ...

Trouble with CSS full height implementation within a scrolling container

I have been grappling with this straightforward issue for quite some time now. It seems to be a unique problem as I couldn't uncover a similar one online. My goal is to set the height of the green bar to 100% (to match the height of the red parent el ...

Click the button to reset all selected options

<form method="post" action="asdasd" class="custom" id="search"> <select name="sel1" id="sel1"> <option value="all">all</option> <option value="val1">val1</option> <option value="val2" selected="selected"> ...

extract elements from dataset

Attempting to splice an array but encountering index issues var kode_pelayanan = []; function deleteKodePelayanan(index){ kode_pelayanan.splice(index, 1); console.log(kode_pelayanan); } Experimented in the console with an array for kode_pelayanan ...

Encountering the 404 Not Found error when trying to fetch the Next.js API Route from the app

Currently facing difficulties with the routing in Next.js 13's app. Every time I attempt to access it, for instance via Postman, I keep getting a 404 Not Found error. This is my file structure: https://i.stack.imgur.com/ZWrlb.png An example of one ...

Update the DOM by setting the innerHTML with a template tag

I'm currently working on a Vue project and I'm facing an issue with setting the innerHTML of an HTML element using a template tag. Here's an example of what I've tried: let divElem = document.getElementById('divElem') let inne ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

Is it possible to deselect a checkbox in a Datagrid Material-ui by clicking a button?

I have set up a grid in Datagrid Material-UI with a checkbox. I am trying to figure out how to uncheck the checkbox by clicking a reset button after it has been checked. For example: https://i.sstatic.net/Za1E6.png This is the DataGrid code I currently ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...