Last days ago, I had an issue to search multi-dimensional arrays in JavaScript / jQuery.
This post will give you a quick example how it works.
First we create an multi-dimensional array.
In my example we create an array for each employee...
var hansi = { firstName: "Hansi", lastName: "Hansen", wage: "2000" };
var paul = { firstName: "Paul", lastName: "Paulsen", wage: "1900" };
var otto = { firstName: "Otto", lastName: "Ottensen", wage: "1500" };
var thomas = { firstName: "Thomas", lastName: "Tomate", wage: "2500" };
...and then push them all together in another array. And here is our multi-dimensional array:
var employees = [hansi, paul, otto, thomas];
Now we want to search for an employee with the first name "Thomas", so we define a variable with the search term:
var searchValue = "Thomas";
Then we use the
grep function from jQuery to search for the term "Thomas" in our multi-dimensional array:
var result = $.grep(employees, function (e) {
return e.firstName == searchValue;
});
Now we just need to check our results variable:
if (result.length == 0) {
alert('Error: ' + searchValue + ' not found');
} else if (result.length == 1) {
employee = result[0];
} else {
alert('Error: Multiple items found');
}
See the results:
Employee Details: First Name: Thomas / Last Name: Tomate / Wage: 2500
Here is the complete code again:
<!DOCTYPE html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var hansi = { firstName: "Hansi", lastName: "Hansen", wage: "2000" };
var paul = { firstName: "Paul", lastName: "Paulsen", wage: "1900" };
var otto = { firstName: "Otto", lastName: "Ottensen", wage: "1500" };
var thomas = { firstName: "Thomas", lastName: "Tomate", wage: "2500" };
var employees = [hansi, paul, otto, thomas];
var searchValue = "Thomas";
var result = $.grep(employees, function (e) {
return e.firstName == searchValue;
});
if (result.length == 0) {
alert('Error: ' + searchValue + ' not found');
} else if (result.length == 1) {
employee = result[0];
} else {
alert('Error: Multiple items found');
}
document.write("Employee Details: ");
document.write("First Name: " + employee.firstName + " / ");
document.write("Last Name: " + employee.lastName + " / ");
document.write("Wage: " + employee.wage + " ");
});
</script>
</head>
<body>
</body>
</html>