Return Largest Numbers in Arrays (sensible place)

Return Largest Numbers in Arrays (sensible place)
0

#1

Hi, coders!
I need help to understand, is my code good enough? and if not, what is it’s sensible place? why it’s bad from practice point of view?

Your code so far

function largestOfFour(arr) {
  // You can do this!
  var newArr =[];
  var final;
  var pushed;
  var separatedArr; 
  var sorted;
  for (var i = 0; i < arr.length; i++){
    separatedArr = arr[i].sort(function (a, b) {
      if (b > a){return b;}       
    });
    sorted = separatedArr.splice(0, 1);
    pushed = newArr.push(sorted);
    final = newArr.reduce(function(flat, current) {
    return flat.concat(current);
    }, []);
    
    console.log(final);
  }
  return final;
 
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:


#2

I’d say if the code works then its probably “good enough”.


#3

hah):grinning: it’s not enough if i want to be better!


#4

You might find the hint section for an exercise quite helpful. Even after you’ve found a solution check it out and see what FCC recommends.


#5

great idea, thanks! I’ll check the fcc solution’s way


#6

In the first line of the function, you declare newArray as an empty array but never use it. I refactored your code by commenting out lines not needed, added one line (see comment I made beside it), and change the variable name which is returned at the very end of the function. You were making a lot of unnecessary extra steps, but you had everything you needed in separatedArr’s first element.

function largestOfFour(arr) {
  // You can do this!
  var newArr =[];
  // var final;
  // var pushed;
  var separatedArr; 
  // var sorted;
  for (var i = 0; i < arr.length; i++){
    separatedArr = arr[i].sort(function (a, b) {
      if (b > a){return b;}       
    });
    newArr.push(separatedArr[0]); // first element contains largest number
    // sorted = separatedArr.splice(0, 1);
    // pushed = newArr.push(sorted);
    // final = newArr.reduce(function(flat, current) {
    // return flat.concat(current);
    // }, []);
  }
  return newArr; // changed from final to newArr
}

#7

thats what I needed! Thank you very much!!! The reason, why I did so many extra steps, because of I don’t understand how exactly to use push() etc. When I try to apply them, the messages like “… is not a function” a little bit overwhelming me. So I’ve tryed to split solvation on little steps (and as you see, made so many steps, so even forget remove some extra of them))). Thanks for your help!