PROBLEM: I need to merge the columns by identifying the headernames and they work as desired by using the below code.
The code is very inefficient as I am using an eval to accomplish the job and I believe it makes unnecessay multiple passes which is not recommended. Is there a way I can optimize my code to merge the columns? My code works good only for one item fruits since "CriteriaMatchArray" for many items I need to pass the result again as input and run it making inefficient.
https://docs.google.com/spreadsheets/d/18FSwIDZ5H5nqrbwq-VIMoHouW6f0cSZ7sTIgN9RxBc0/edit?usp=sharing
Here is the image : https://i.sstatic.net/A2d6d.png
Hence the end result is nothing but 2d array as shown in the image
I have code below
<!DOCTYPE html>
<html>
<body>
<script>
var table = [
["Sl.no","fruits 1", "fruits 2", "fruits 3", "fruits 4", "fruits 5", "vegetables 1", "vegetables 2"],
["1","banana", "apple", "orange", "", "", "carrot", "cabbage"],
["2","watermelon", "apple", "orange", "", "", "beans", ""]
]
//document.write(JSON.stringify(table))
var str = [],
m = [];
var firstJoiningPosition = -1;
CriteriaMatchArray = ["fruits"] //this is the input (currently processes only 1 item in list) and user can change or add more
for (var i = 0; i < table[0].length; i++) {
if (table[0][i].indexOf(CriteriaMatchArray[0]) == -1) {
str.push("table[i][" + i + "]")
} else {
if (firstJoiningPosition == -1)
firstJoiningPosition = i
m.push("table[i][" + i + "]")
}
}
str[firstJoiningPosition] = m.join("+ '#' +")
evalstring = str.join(",")
document.write('<pre>Given table ' + JSON.stringify(table, null, 4) + '</pre>')
var result = []
for (var i = 0; i < table.length; i++) {
eval("result.push(" + "[" + evalstring + "]" + ")")
}
document.write('<pre>Result after joining ' + JSON.stringify(result, null, 4) + '</pre>')
</script>
</body>
</html>