2

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]]);
5
  • .sort sorts the array in place, so arr[i][0] will work fine. Are you asking whether there is a shorter way to do this? FWIW, newArr is completely useless here. Commented Nov 17, 2015 at 21:58
  • Right now the sort method sorts the arrays just fine. The problem is accessing those sorted arrays. When I try and access them outside of the .sort() function, I get the original (unsorted) arrays. Commented Nov 17, 2015 at 22:00
  • I doubt that. arr[i][0] will give you the largest value. Again, the issue is rather that you are not doing anything with newArray. Commented Nov 17, 2015 at 22:01
  • arr[i][0] is currently resulting in: Cannot read property '0' of undefined. Commented Nov 17, 2015 at 22:04
  • No it doesn't: jsfiddle.net/tsgLj0sv . Your code executes fine. But again, you are not doing anything with newArr, and you are creating a new array in each iteration. Commented Nov 17, 2015 at 22:06

4 Answers 4

4

You don't even need to sort the array. You could use Math.max.

function largestOfFour(arr) {
  return arr.map(function (el) {
    return Math.max.apply(null, el);
  });
} // [ 5, 27, 39, 1001 ]

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

nice... you win (as long as it's a number... as long as it's a number). :-)
2

Like this?

function largestOfFour(arr) {
  var results = [];
  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
    });
    results.push(arr[i][0]);
  }
  return results;
}

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

1 Comment

That works, yep! Thanks a lot! I marked Andy's answer as the correct answer, however - only because it makes use of a shorter method!
1

Is it possible to access a returned value from a function/code block that is nested inside another code block?

You can only get the return value if you call the function. You are not calling the .sort callback, it is called inside .sort, so you cannot get its return value.


I assume you are asking because the code you have doesn't work as you expect. Looking at your code, it appears obvious that, while you sort the array, you are not really doing anything with it after you sorted it. As I already said in my comments, the way you use .sort and access the largest value is perfectly fine.

I think you want to declare newArr outside the loop and return it from the function:

function largestOfFour(arr) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    arr[i].sort(function(a, b) {
      return b - a;
    });
    newArr.push(arr[i][0]);
  }
  return newArr;
}

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

There is also a more streamlined way of writing this, that doesn't mutate the input array:

function largestOfFour(arr) {
  return arr.map(function(innerArray) {
    return innerArray.reduce(function(a, b) {
      return a > b ? a : b;
    });
  });
}

5 Comments

Unfortunately, that results in the same thing. I'm still only getting the original, unsorted arrays. return newArr doesn't output anything, either.
I had a typo, but other than that it works perfectly fine. Try it again.
Thanks! I marked Andy's answer as the correct one, though. Only because it seems to be a more efficient method (without using sort).
@Jose: In that case I suggest to update your question and reformulate it to ask what you really want to know. Because, while the accepted answer fixes your code, it doesn't seem to answer your question.
TBF I should write a bit more in my answer :) But it was really meant as an "As an aside..."
0

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:

Try using while loop , .push() .sort() , .reverse() . largestOfFour returns two arrays , whose indexx can be toggled at return statement ; largest number from each array at first array , arrays in array sorted from largest to least at second array

function largestOfFour(arr) {
  var res = [], i = arr.length - 1;
  while(i > -1) {
    res.push(Math.max.apply(Math, arr[i].sort(function(a, b) {
      return Number(b) - Number(a)})
      )); 
  --i;
  };     
  return [res, arr.reverse()]
}

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

function largestOfFour(arr) {
  var res = [], i = arr.length - 1;
  while(i > -1) {
    res.push(Math.max.apply(Math, arr[i].sort(function(a, b) {
      return Number(b) - Number(a)})
      )); 
  --i;
  };     
  return [res, arr.reverse()]
}

document.getElementsByTagName("pre")[0]
.textContent = JSON.stringify(largestOfFour(input), null, 2);
<pre></pre>

5 Comments

Why sort if you use Math.max anyway?
You don't need to sort the array as well as use Math.max.
@FelixKling "Why sort if you use Math.max anyway? " As interpreted here from OP "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:", two separate return results were expected; 1) sorted arrays, 2) max of each sorted array
Ah I see. But in that case I would use return val[0]; instead of Math.max. (I assumed the OP only sorted in order to get the largest value).
@FelixKling "But in that case I would use return val[0]; instead of Math.max." Yes, that would be briefer . Have to ingrain to use array notation where possible . If single array was expected , could use [0] within first .map() at .sort() to avoid any further calls

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.