Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!