1

I have a function in one of my controllers where I populate an array of references to a document, which, when populated, have embedded arrays themselves.

Here's an example:

The mongoose populate function gives me an array of objects. Within each of those objects is an array:

[{ name: Test, array: [ 1, 2, 3, 4, 5 ] }, { name: TestAgain, array: [1, 2, 3, 4, 5] }, { name: Test^3, array: [1, 2, 3, 4, 5]}, {...

The desired output would be:

[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...]

I need to concatenate all of the "arrays" within the populated references. How can I do this without knowing how many arrays there are?

For reference, here is (generally) what my function looks like:

exports.myFunctionName = function ( req, res, next )

Document.findOne({ 'document_id' : decodeURIComponent( document_id )}).populate('array_containing_references').exec(function( err, document) 
{
   //Here I need to concatenate all of the embedded arrays, then sort and return the result as JSON (not worried about the sorting).
});
1
  • That's not clear at all. simplify this by 2 factors at least (since it looks like you're after something very simple). Show input, desired output, and what you've tried so far. Commented Jul 15, 2015 at 22:11

2 Answers 2

1

Assuming your input is in the document variable, try this:

var output = document.reduce(function (res, cur) {
  Array.prototype.push.apply(res, cur.array);
  return res;
}, []);

Or this:

var output = [];
document.forEach(function(cur) {
  Array.prototype.push.apply(output, cur.array);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@RobG - yeah.. that was an afterthought... fixing
1

You want to take each document and do something with a property from it. Sounds like a great use case for Array.prototype.map!

map will get each document's array value and return you an array of those values. But, you don't want a nested array so we simply use Array.prototype.concat to flatten it. You could also use something like lodash/underscore.js flatten method.

var a = [
  { name: 'test1', array: [1, 2, 3, 4, 5]}, 
  { name: 'test2', array: [1, 2, 3, 4, 5]}, 
  { name: 'test3', array: [1, 2, 3, 4, 5]}
];

var results = Array.prototype.concat.apply([], a.map(function(doc) { return doc.array; }));

document.body.innerHTML = results;

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.