Use loops to write efficient JavaScript

Updated at September 15th, 2022

The forEach loop method in Javascript iterates over the elements of an array and calls the provided function for each element in order. You can use forEach loops to avoid writing repetitive code in your data process.

In data process, you might want to make the same type of change to many elements. For example, you might create sums across products for two groups, S10v1 and S10v2

One method is to create each of the new elements individually. This leads to many lines of similar code, and it is more prone to mistakes. If you want to go back and make changes to the logic it can be a tedious process. 

var rows = data["main"]

rows.forEach(function(row) {
    row.S10v_sum_1 = (+row.S10v1_1) + (+row.S10v2_1)
    row.S10v_sum_2 = (+row.S10v1_2) + (+row.S10v2_2)
    row.S10v_sum_3 = (+row.S10v1_3) + (+row.S10v2_3)
    row.S10v_sum_4 = (+row.S10v1_4) + (+row.S10v2_4)
    row.S10v_sum_5 = (+row.S10v1_5) + (+row.S10v2_5)
    row.S10v_sum_6 = (+row.S10v1_6) + (+row.S10v2_6)
    row.S10v_sum_7 = (+row.S10v1_7) + (+row.S10v2_7)
    row.S10v_sum_8 = (+row.S10v1_8) + (+row.S10v2_8)
    row.S10v_sum_9 = (+row.S10v1_9) + (+row.S10v2_9)
    row.S10v_sum_10 = (+row.S10v1_10) + (+row.S10v2_10)
    row.S10v_sum_11 = (+row.S10v1_11) + (+row.S10v2_11)
    row.S10v_sum_12 = (+row.S10v1_12) + (+row.S10v2_12)
    row.S10v_sum_13 = (+row.S10v1_13) + (+row.S10v2_13)
    })
return rows;

A more efficient way to do the same thing across many elements is to create a forEach loop function. Instead of writing one line of code for each of the 13 products, create an array that includes each product suffix [1,2,3…13].

In the example below, the loop iterates over each value within the array. 

var rows = data["main"]
rows.forEach(function(row) {
    // Loop to create new elements that sum across each product type for S10v1 and S10v2 
        [1,2,3,4,5,6,7,8,9,10,11,12,13].forEach(function(product){
            row["S10v_sum_"+product] = (+row["S10v1_"+product]) + (+row["S10v2_"+product])
    })
})
return rows;

Notice in the code we've put a "+" before each value we want to add. The + operator immediately before a variable will return the numeric representation of the variable. This will ensure a number will be evaluated as a number rather than as a string, and be added numerically (2+7=9) not alphabetically ("2" + "7" = "27").

Reminder: For data processes, "Save" and "Run" the process after you are done editing the code view. To use the result of the process as the primary data for the project, you will need to set it as "Primary".

Data processes are specific to each project, and your code may not look identical to our example.

 

Was this article helpful?