Ryepower
Ryepower

Reputation: 181

how to return the two largest number from each array of an array in JavaScript without using for loops?

    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!

Upvotes: 0

Views: 93

Answers (3)

void
void

Reputation: 36703

You need to sort the array as well if it not sorted

function theHighest(data) {
        let twoLargest = data.map((x) => {
            // Get two largest integers
            return x.sort().slice(-2);
        })
        // Flatten the array
        return Array.prototype.concat(...twoLargest);
    
    }
   
    console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68443

You can also use reduce and sort

var output = arr.reduce( (a, c) => a.concat(c.sort().slice(-2)), [] );

outputs [2,3,4,5,7,8]

Demo

var arr = [[1, 2, 3], [3, 4, 5], [6, 7, 8]];

var output = arr.reduce( (a, c) => a.concat(c.sort().slice(-2)), [] );

console.log( output );

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could take a copy, sort the array and return the two max values.

function theHighest(data) {
    return [].concat(...data.map(a => a.slice().sort((a, b) => a - b).slice(-2)));
}

console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]));

Upvotes: 2

Related Questions