function theHighest(data) {
let twoLargest = data.map((x) => {
return x.reduce((prev, curr) => {
return curr
})
})
return twoLargest //returns [3,5,8]
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))
The above function can return the largest numbers in each array and if it could return prev along with curr in the same array the job would be done and the desired result would be achieved which is [2,3,4,5,7,8] How can I return this without using for loops at all?
If I use for loops here is how I do it:
function theHighest(data) {
let highestValues = []
for (let i = 0; i < data.length; i++) {
let first = 0
let second = 0
for (let j = 0; j < data[i].length; j++) {
if (first < data[i][j]) {
second = first;
first = data[i][j];
}
else if (second < data[i][j]) {
second = data[i][j];
}
}
highestValues.push(first, second)
}
return highestValues
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))
Thank you!
previn yourreducefunction is the output of the previous iteration. You can set it to an array of the largest two numbers so far.mapaslicethat takes the last two entries.