Code Lab

Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado

Negative numbers to the left

MediaArrays10 min

Write a function groupNegatives(numbers) that returns a new array with the negative numbers on the left: first all negative numbers, then all other numbers.

  • numbers is an array of integers. It can be empty.
  • 0 is not negative: it goes to the right group, together with the positive numbers.
  • Keep the order inside each group as in numbers. [-5, 10, -3, 8, -1, 6] gives [-5, -3, -1, 10, 8, 6]. Do not sort the numbers.
  • Return a new array. Do not change (do not mutate) numbers.

Each element goes to one of two groups. filter can pick the elements of one group.

Ejemplos

groupNegatives([-5, 10, -3, 8, -1, 6])

Devuelve [ -5, -3, -1, 10, 8, 6 ]

groupNegatives([4, -7, 0, 2])

Devuelve [ -7, 4, 0, 2 ]

Preguntada en ServiceNow · Fuente

Cargando el editor…
  1. EntradagroupNegatives([ -5, 10, -3, 8, -1, 6 ])
    Esperado[ -5, -3, -1, 10, 8, 6 ]
  2. EntradagroupNegatives([ 4, -7, 2 ])
    Esperado[ -7, 4, 2 ]

Las pruebas ocultas se ejecutan al enviar