The below arrays are just examples of how I need it to function. I've created a for loop to append elements to a matching row, and now I'm trying to work out removing the previous row.
example array:
[sally, yes, brown, 5],
[david, yes, blue, 8],
[sally, yes, green, 3],
[sally, no, yellow, 7],
[david, no, green, 3],
[ben, no, purple, 12]
desired output:
[sally, yes, brown, 5, yes, green, 3, no, yellow, 7],
[david, yes, blue, 8, no, green, 3],
[ben, no, purple, 12]
So, what I want the code to do is this:
- Checking if an element appears in the first column more than once, but doesn't have the same value from column 3.
- When the above is true, copy the 2nd, 3rd, and 4th elements from that row(j) to the row where the element first appeared.
- Remove the other rows where the element appears.
My current code for this loop is below. Not sure why it's wrong, but it's not getting the above result.
for (i = 0; i <data.length; i++){
for (j=0; j<data.length; j++){
var count = 0;
if(data[i][0] == data[j][0]){
count++;
if (data [i][2] != data[j][2]){
data[i].push(data[j][1], data[j][2], data[j][3], data[j][4])
if (count > 1){
data.splice(i-1 ,1);
}
}
}
}
}
I might be going about this the wrong way, so if there is another method to solve it that you suggest instead of this for loop, that would be greatly helpful. Would it work better/ be easier to compare two separate arrays instead of comparing the array to itself?
Additionally, after solving this portion of the code, I will need to add empty elements to all rows that are shorter than the longest. In the case of the above example dummy data, the longest is 10 columns long, so I would need to add empty spaces in varying amounts to any row shorter than that. The reason is that I am pasting it to a spreadsheet afterwards but can't do that with .setValues method unless the length is the same for every row. If anyone could help with that as well, that would be appreciated also.