Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
How do you group an array by n and the number of decreasing integers (n-1)? With the output to be the total number of arrays

For example, this is the input array: [2, 1, 4, 4, 3]

From this array, n-1 patterns will be established from left to right.

This output would be the number 7 because the following separate arrays exist after grouping:

[2] [1] [4] [4] [3] - 1 group (n)

[4, 3] - 1 group (n-1)

[2, 1] - 1 group (n-1)

Output: 7 (arrays)

This is what I started so far, but it looks like I just summed everything together.

let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);

It would be appreciated if the solution and an explanation is provided in JavaScript. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Script:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  // remove duplicates
  let unique = [...new Set(numbers)];
  // get length of unique array, then add to the length of filtered unique array where it also contains n-1
  console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
}

Get the number of unique elements then add it to the length of the filtered unique array where it also contains n-1.

Output:

output

If you want to get the arrays:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  let unique = [...new Set(numbers)];
  var arrays = [];
  unique.forEach(number => {
    arrays.push([number]); 
    if(numbers.includes(number - 1))
      arrays.push([number, number-1])
  });

  console.log(arrays.length)
  console.log(arrays)
}

output2

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda