I need to return an array consisting of the largest number from each provided sub-array. So, I've written the following code and it works but I have: [[25],[48],[21],[-3]]
instead of [25,48,21,-3]
. Can I change something to get the right answer?
function largestOfFour(arr) { for (let i = 0; i < arr.length; i++) { arr[i].sort(function(a,b) { return b - a; }).map(function() { return arr[i].splice(1); }) } return arr; } var result = largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]); console.log(result);
You could use map
with spread syntax ...
to return 1D array as pointed out by @str .
function largestOfFour(arr) { return arr.map(a => Math.max(...a)) } const arr = [[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]] const result = largestOfFour(arr); console.log(result)
You could also use reduce
function largestOfFour(arr) { return arr.reduce((r, a) => r.concat(Math.max(...a)), []) } const arr = [[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]] const result = largestOfFour(arr); console.log(result)
Loop and sort, then return the first element of each sub-array with map
;
function largestOfFour(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i].sort(function(a,b) {
return b - a;
});
}
return arr.map(array => array[0]);
}
Better still, do it in one.
function largestOfFour(arr) {
return arr.map(array => array.sort((a,b) => b - a)[0]);
}
get the first character of each array using [0]
index like this
function largestOfFour(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i].sort(function(a,b) {
return b - a;
}).map(function() {
// HERE
return arr[i].splice(1)[0];
})
}
return arr;
}
largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]);
You could map the first element of the descending sorted elements.
function largestOfFour(array) { return array.map(a => a.sort((a, b) => b - a)[0]); } console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));
You can use map
which will return a new array and then use Math.max
to get the maximum value form the array
function largestOfFour(arr) { return arr.map(item => { return [Math.max.apply(null, item)] }) } console.log(largestOfFour([ [17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10] ]));
you can use flat function for it
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.