As of ol3 recent versions, it's very easy to create a function that can be invoked whenever you need to grab a layer (whether in a group or not).
The other answers are fine as well, I only include this code here because of it's ease of adaptation for whatever you need, and being a newb once this type of snippet really helped me out- here's giving back to the community.
Best is to invoke a callback any place you need it:
function needMeSomeLayers () {
var layerArray = getAllofEm();
layerArray.forEach(layer, function() {
// do something with them
})
}
where the function called:
function getAllofEm () {
var allLayers = [];
var mapLayers = map.getLayers().getArray();
mapLayers.forEach(function (layer, i) {
if (layer instanceof ol.layer.Group && layer.getVisible() == true ) {
layer.getLayers().getArray().forEach(function(sublayer, j, layers) {
allLayers.push(sublayer);
})
} else if ( !(layer instanceof ol.layer.Group) && layer.getVisible() == true ) {
allLayers.push(layer);
}
});
return allLayers;
}
walks through all of the layers. In this example I test for visibility, but the
&& layer.getVisible
can be removed depending on cause, or used after the callback (in the forEach, for instance).
This is one of the most used utilities across all of the work I do with ol3, something that's great to have in the toolkit.