Javascript Map and Join function

Map: The map method creates a new array with the results of calling a provided function on every element in the calling or existing array. We have to supply an array, runs that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case or add create ) and subsequently returns a new array once completed.

The array.join() method is an inbuilt function in JavaScript which is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).

In this example, we will create an array of query params into a string by using both map and join. The output of our example
Value WHERE dated >= ‘2019-08-12’ and dated <= ‘2019-09-12’ and name = ‘edupala’

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript map function</h2>

<p id="mapValue"></p>

<script>
function wheresSql(wheres) {
    return wheres.length ? 'WHERE ' + wheres.map((where) => {
        return where.field + ' ' + where.operator + ' \'' + where.value.replace('\'', '\'\'') + '\''
    }).join(' and ') : '';
}

let wheres = [
{field: "dated", operator: ">=", value: "2019-08-12"},
{field: "dated", operator: "<=", value: "2019-09-12"},
{field: "name", operator: "=", value: "edupala"}
];

document.getElementById("mapValue").innerHTML = "Value  " + wheresSql(wheres);
</script>

</body>
</html>

Leave a Comment

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

Scroll to Top