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?

Urban
  • 585
  • 2
  • 13
  • 28

2 Answers2

0

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

Community
  • 1
  • 1
anoop
  • 3,812
  • 2
  • 16
  • 28
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 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? – Urban Mar 24 '17 at 11:11
  • I mean the collectionID object isn't always the second of the array. – Urban Mar 24 '17 at 11:17
  • Thank you very much! Really helped me a lot. – Urban Mar 24 '17 at 11:30