I've been wondering... Is it possible to access a returned value from a function/code block that is nested inside another code block?
For example, I am trying to sort values in an array from largest to smallest using the .sort() method, and then take the largest from each nested array and push it to a new array:
function largestOfFour(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
arr[i].sort(function(a,b) {
return b - a; // trying to access this new, organized array
});
var newArr = [];
newArr.push(arr[i][0]);
}
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
.sortsorts the array in place, soarr[i][0]will work fine. Are you asking whether there is a shorter way to do this? FWIW,newArris completely useless here.arr[i][0]will give you the largest value. Again, the issue is rather that you are not doing anything withnewArray.newArr, and you are creating a new array in each iteration.