3

I am querying a mongo database using a javascript file. I have a for loop and I am adding to myArray using myArray.push(value).

My problem is when I run the script in Robomongo I get 2 outputs - the length of the array(which I don't want) and the print statements(I want).

Is there anyway to prevent the script from outputting the length of the array - is there another function I should be using other than .push???

Here is some of the script:

var myArray = [];
var result = jobData['result'];

for(var i = 0; i < result.length; i++){
    var collection = result[i].Tolerances;
    for(var j = 0; j < collection.length; j++){
        var cur = collection[j];
        myArray.push(cur);      // I do not want this value outputted
    }
}
for(var x = 0; x < myArray.length; x++){
    var value = myArray[x];
    print("Currency From: "+value.FromCurrency+";Currency To: "+value.ToCurrency+";Tolerance: "+value.TolerancePercentage+");
};

If there is more detail required just let me know.

1 Answer 1

3

You can use JavaScript's reduce() and map() methods to construct the new array without logging the length of the new array. The following example demonstrates how to use these two methods in your case:

var jobData = {
    result: [
        { Tolerances: ["foo", "bar"] },
        { Tolerances: ["abc", "def"] },
        { Tolerances: ["123", "456"] }
    ]
};
var myArray = [];
var result = jobData['result'];  

var tolerances = result.map(function (r){
    return r.Tolerances;    
});

myArray = tolerances.reduce(function (a, b){
    return a.concat(b);
});

printjson(myArray);
// prints ["foo","bar","abc","def","123","456"]

Check the demo below.

var jobData = {
	result: [
		{ Tolerances: ["foo", "bar"] },
		{ Tolerances: ["abc", "def"] },
		{ Tolerances: ["123", "456"] }
	]
}
var myArray = [];
var result = jobData['result'];


var tolerances = result.map(function (r){
	return r.Tolerances;	
})

myArray = tolerances.reduce(function (a, b){
	return a.concat(b);
})

pre.innerHTML = "myArray: " + JSON.stringify(myArray, null, 4);
<pre id="pre"></pre>

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

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.