0

I'm just getting started on learning javascript, and I'm creating this simple program that takes the largest numbers from an array, and put them in a new array, which will be returned in the end.

The function is called largestOf(), and for example,

largestOf([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].

What I have so far is this, and I don't know how to fix it, or if it has something to do with the way I am utilizing the brackets.

function largestOf(arr) {
    var nArr = [];
    for (var i = 0; i < arr.length; i++) {
        n = arr[i].length;
        max = 0;
        for(var j = 0; j < n; j ++) {
            if (arr[i][j] > max) {
                max = arr[i][j];
                nArr.push(max);
            }
         }
    }

    return nArr;
}

What I am trying to do here is pretty straightforward. I'm running through every block in the array, picking the max, and putting that max in its own array (nArr) with the other max's.

I want to know how to fix what I have while still doing it my way.

Thank you

5
  • 1
    Please show us what you want as a result and what the current problem is. Commented Jan 7, 2016 at 19:05
  • You just need to move the .push() call to outside the inner for loop. Commented Jan 7, 2016 at 19:05
  • I'd start by placing nArr.push(max) after the for loop. Commented Jan 7, 2016 at 19:05
  • code golf jsfiddle.net/johnboker/2pf41suu Commented Jan 7, 2016 at 19:14
  • Welcome to SO! If the proposed answer works for you, please consider accepting it as well. This is the SO system to thank people. Of course a nice comment is always highly appreciated as well! Commented Jan 7, 2016 at 20:14

1 Answer 1

2
function largestOf(arr) {
    var nArr = [];
    for (var i = 0; i < arr.length; i++) {
        var n = arr[i].length;
        var max = 0;
        for (var j = 0; j < n; j++) {
            if (arr[i][j] > max) {
                max = arr[i][j];
            }
        }
        nArr.push(max); // push your max outside of the inner loop
    }
    return nArr;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.