Pushing values to an array from within a for-loop (within another for-loop) JavaScript

I’m trying to check if the numbers in an array can add up to a specific number in the array (in this case the arrays largest number is the target). My thought process was to create an array of all the possible combinations and then iterate over it to see if the largest number is in there.

To get the array (the addArray function) of all the combinations I created an array, results = [0], and am trying to iterate through each value in the array being tested, e.g array1, and add each value to results and push these results into results as I go along. So, using array1 as an example:

results = [0] and array1[0] = 5; 0+5 is pushed to results so: results = [0, 5];

results = [0, 5] and array1[1] = 7; 0+7 and 5+7 is pushed to results so results = [0, 5, 7, 12];

etc,

In order to achieve this I created a for loop to iterate through the array being tested and then within that for loop I created another for loop to iterate through the results array and then push the sum of the item in the array being tested with all the items in results, such that when the loop moves into the next item of the original array, when it gets to the second for loop the results array contains the sums of the previous items as illustrated in the example above.

However, I can’t seem to get it to work, although if I put some values in results I can see that each item is being iterated over every value in results. My problem seems to be pushing the items to results for the next item in the original array. My feeling is that you can’t push items to an array you’re iterating over? Any help would be greatly appreciated.

Thanks

var array1 = [5, 7, 16, 1, 2];
var array2 = [3, 5, -1, 8, 16];
var array3 = [4, 6, 23, 10, 1, 3];

var arraySort = function(arr) {
    arr = arr.sort(function(a, b) {
        return a - b;
    });
    return arr;
};

var addArray = function(arr) {
    arr = arraySort(arr);
    var largest = arr[arr.length - 1];
    var results = [0];
    //Here's where I am stuck.
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < results.length; j++) {
            results.push(arr[i] + results[j]);
        }
    }
};
addArray(array1);

Answer

Try this,

var addArray = function(myarr) {
    var arr = myarr.slice(0).sort((a,b)=>a-b);
    var new_results = [];
    var results = [0,5];
    //Here's where I am stuck.
    for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < results.length; j++) {
            new_results.push(arr[i] + results[j]);
        }
    }
    return new_results;
};

console.log(addArray([0,1,2]).sort());

You were appending to result array which was infinitely increasing in the for loop. Use a different array to store results, and also, ideally always slice an array which is passed as argument.

Leave a Reply

Your email address will not be published. Required fields are marked *