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.
CodePudding user response:
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));
CodePudding user response:
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))