I'd like to pass an array element as a parameter to my function.
I have an array and my array has Column1 and Column2 elements. My code is sorting the array according to column1 or column2. Right now, I'm passing the 1 and 2 values as a parameter and I have an if condition in my sorting code.
I want to change my code like:
function sortGrid(ColumnName)
and
var val1 = a.ColumnName.toLowerCase()
Do you have any 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>
2 Answers 2
You can do that with a[ColumnName]:
var arr = [{"Column1":"A","Column2":"F"},{"Column1":"Z","Column2":"B"}];
function sortGrid(colName) {
arr.sort(function (a, b) {
var val1 = a[colName].toLowerCase();
var val2 = b[colName].toLowerCase();
return val1 < val2 ? -1
: val1 > val2 ? 1
: 0;
});
}
sortGrid('Column1')
console.log(arr[0].Column1)
console.log(arr[1].Column1)
console.log('-------------------')
sortGrid('Column2')
console.log(arr[0].Column1)
console.log(arr[1].Column1)
Note that you should return 0 when the values are equal, so I have used the ternary operator (twice) with a 0 in it as well.
2 Comments
<!--- ... --> tags inside your text which will do the trick.Your code could be something like:
var arr = [{"Column1":"A","Column2":"F"},{"Column1":"Z","Column2":"B"}];
function sortGrid(colName) {
arr.sort(function (a, b) {
var val1 = a[colName].toLowerCase();
var val2 = b[colName].toLowerCase();
if (val1 < val2)
return -1
if (val1 > val2)
return 1
});
}
sortGrid('Column1')
console.log(arr[0].Column1)
console.log(arr[1].Column1)
console.log('-------------------')
sortGrid('Column2')
console.log(arr[0].Column1)
console.log(arr[1].Column1)
Just one more thing: if you use var to declare local variables, then their scope is the whole function, so your code is declaring them twice. It will work but is unnecessary.
Comments
Explore related questions
See similar questions with these tags.
a.ColumnName(which wont work), doa[ColumnName]: that is the dynamic way.