2
\$\begingroup\$

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>

\$\endgroup\$
2
  • \$\begingroup\$ is this a task for university? seems rather unusual and far from a reality case \$\endgroup\$ Commented Aug 24, 2021 at 8:34
  • 1
    \$\begingroup\$ This is not an assignment from University. But it is something related to a prototype project research. This is a problem for generating the CSV from the fetched results of API, The API provides more detailed columns and we need to join the column data like we have in gmail contacts, the groups are being merged and separated by::: symbol, similarly the system we build needs to have some data to be concatenated. \$\endgroup\$ Commented Aug 24, 2021 at 8:58

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.