1

Just starting to learn Javascript and Angular. I have an array within an array.

This is my array structure:

[[object1, object2],[object3, object 4]];

I want to get the highest value from object2 and object 4.

When i only had one array i used

Math.max.apply(Math, array.map(function(o){return o.collectionID;}));

Is it possible and how can i retrieve the highest value from an array within an array?

2
  • apply it to parentArray[n]? Commented Mar 24, 2017 at 10:50
  • Can you post your array structure? Commented Mar 24, 2017 at 10:51

2 Answers 2

0

You could collect all id with Array#reduce for any depth arrays.

Then take only collectionID where it is set.

var array = [[{}, { collectionID: 1 }], [{}, { collectionID: 2 }], [{}, { collectionID: 3 }], [{ collectionID: 42 }, { collectionID: 4 }]],
    max = Math.max.apply(Math, array.reduce(function iter(r, a) {
        return r.concat(Array.isArray(a) ? a.reduce(iter, []) : 'collectionID' in a ? a.collectionID : []);
    }, []));
    
console.log(max);

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

3 Comments

Thanks for the fast response! My array format is [[{object},{collectionID: 1}],[{object},{collectionID: 2}]] How could i choose the second object in the array?
I mean the collectionID object isn't always the second of the array.
Thank you very much! Really helped me a lot.
0

Here is the very simple and powerful answer [https://stackoverflow.com/a/23397247/3455035]

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.