Home > Software design >  A function separating numbers from Arrays to positive and negative numbers
A function separating numbers from Arrays to positive and negative numbers

Time:11-10

friends. I want a function, when I give it arrays, that function will seperate positive and negative numbers from those arrays and push them to negativeNumbers or positiveNumbers.

But as you see below, I can do it for arrayOne. If I want do it with arrayTwo, I have to copy all codes again. Is there any way, I create one function, and use that function for all arrays?

For example, checkValue(arrayOne), checkValue(arrayTwo), etc.

Thank you in advance!

const negativeNumbers = []
const positiveNumbers = []
const arrayOne = [-2, 5, -3, 6]
const arrayTwo  = [-12, 15, -13, 16]
const checkValue = arrayOne.forEach((element) => {
    if (element<0){
        negativeNumbers.push(element)
       } 
    if (element>=0) {
        positiveNumbers.push(element)
    }
}) 
console.log(positiveNumbers)
console.log(negativeNumbers)

CodePudding user response:

You can turn that into a function that accepts an array and returns two arrays in the form of [array, array] or {arr1: array, arr2: array}

const arrayOne = [-2, 5, -3, 6]
const arrayTwo = [-12, 15, -13, 16]

function split_by_sign(arr) {
  const negativeNumbers = []
  const positiveNumbers = []

  arr.forEach((element) => {
    if (element < 0) {
      negativeNumbers.push(element)
    }
    if (element >= 0) {
      positiveNumbers.push(element)
    }

    // btw, what about zero?
  })
  
  return [positiveNumbers, negativeNumbers]
}

console.log("arrayOne splitted: ", split_by_sign(arrayOne))
console.log("arrayTwo splitted: ", split_by_sign(arrayTwo))

// or practical usage: 
var [positive, negative] = split_by_sign(arrayOne)
console.log("positive of array1: "   positive)
console.log("negative of array1: "   negative)

CodePudding user response:

Here's a simpler version of @ITgodman's answer using Array#filter.

function splitNegativePositive(array){
  return {
    positives: array.filter(n => n >= 0),
    negatives: array.filter(n => n < 0),
  }
}

const input1 = [-1, 5, 9, 0, -3];
const input2 = [-10, -5, 7, 0, 3];

console.log({
  input1,
  input1Output: splitNegativePositive(input1),
  input2,
  input2Output: splitNegativePositive(input2),
})

  • Related