Search code examples
javascriptarrayscomparison

Find the array with the largest number in a 2d array with Javascript


This is my attempt and it works fine, but I need to return the array containing the largest number, not the largest number itself.

Also, I want to know if there is a way to use deep-equal to compare inner arrays in 2D arrays.

function largestOfFour(arr) {
	for (var i = 0; i < arr.length; i++) {
		var largest = [0][0];
		for (var j = 0; j < arr[i].length; j++) {
			if (arr[i][j] > largest) {
				largest = arr[i][j];
			}
		}
	}

	return largest;

}

var largest = largestOfFour([
	[4, 5, 1, 3],
	[13, 27, 18, 26],
	[32, 35, 37, 39],
	[1000, 1001, 857, 1]
]);

console.log(largest);


Solution

  • Create another variable and store the arr[i] array at the same time that you note the biggest number. You could remove largest variable if you only need the largest array (or replace largestOrigin by it).

    JavaScript

    function largestOfFour(arr) {
        var largest = 0,
            largestOrigin = [];
    
        for(var i = 0; i < arr.length; i++){ 
            for (var j = 0; j < arr[i].length; j++) {
                if(arr[i][j] > largest){
                    largest = arr[i][j];
                    largestOrigin = arr[i];
                }
            }
        }
        return largestOrigin;
    }
    
    largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
    // Returns  [1000, 1001, 857, 1]
    

    JSFiddle (live demo)