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

119
Views
Concurrent Array Functions

I have a function that takes an array of sub-arrays containing number strings and returns an array with the highest number from each sub-array:

const largestOfFour = arr => {
            arr.map(e => {
                e.sort((a,b) => b - a).splice(1);
            });
            return arr.flat();
        } 

It works perfectly in the way it is formatted above but it does not work if it is formatted with concurrent functions on the array passed in. Like this:

const largestOfFour = arr => {
            return arr.map(e => {
                e.sort((a,b) => b - a).splice(1);
            }).flat();
        }

In that format it returns an array of appropriate length but each element is null. Can anyone help me understand why that is? I usually don't have a problem chaining concurrent functions onto an array.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

There is no concurrency in JavaScript. But your map callback does not return anything (there is no return in the statement block) so .map() returns an array of undefined values.

To avoid that the original data gets mutated, I would also avoid the use of sort on the original array, and use slice instead of splice.

But as you only need one value from each array, you don't even need slice: just get the value at index 0 (making flat unnecessary):

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
];

const largestOfFour = arr =>
  arr.map(e =>
    [...e].sort((a, b) => b - a)[0]
  );

console.log(largestOfFour(a));

Or even better, just use Math.max, which also makes the conversion to number:

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
];

const largestOfFour = arr => arr.map(e => Math.max(...e));

console.log(largestOfFour(a));

about 4 years ago · Juan Pablo Isaza Report

0

The inner block (in map) issn't returning anything, resulting in an array of undefined. Fixed in the snippet...

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
]

const largestOfFour = arr => {
  return arr.map(e => {
    return e.sort((a, b) => b - a)[0];
  }).flat();
}

console.log(largestOfFour(a))

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!