Looking to pass an array element as a parameter in my function.
I have an array with elements Column1 and Column2. The code currently sorts the array based on either column1 or column2. Currently, I am passing 1 and 2 values as parameters with an if condition in the sorting code.
I aim to update the code to:
function sortGrid(ColumnName)
and
var val1 = a.ColumnName.toLowerCase()
Any thoughts or suggestions?
Code:
<html lang="">
<body>
<script>
var arr = [{"Column1":"A","Column2":"F"},{"Column1":"Z","Column2":"B"}];
function sortGrid(col) {
arr.sort(function (a, b) {
if (col == 1)
{
var val1 = a.Column1.toLowerCase();
var val2 = b.Column1.toLowerCase();
};
if (col == 2)
{
var val1 = a.Column2.toLowerCase();
var val2 = b.Column2.toLowerCase();
};
if (val1 < val2)
return -1
if (val1 > val2)
return 1
});
}
sortGrid(1)
console.log(arr[0].Column1)
console.log(arr[1].Column1)
console.log('-------------------')
sortGrid(2)
console.log(arr[0].Column1)
console.log(arr[1].Column1)
</script>
</body>
</html>