Javascript implementation question: how to make this function display values
-
29-09-2019 - |
문제
Please forgive me, but I do know js basics and how to write/call a basic function, but in this case I'm trying to match an alpha sorted list of categories from the DB to match against my set (non-alpha) order of said categories as specified below (this is code suggested for use by another user on a question I asked about how to map the order of categories being returned). However, I can't figure out how to integrate that person's code answer into my own code.
Just seeing it implemented against another example list (to mimic what I would grab from the DB) and how I would call it in a switch case statement to wrap my html around the category names and return them to the web page in the mapped order I want would help a great deal. Sorry if it turns out to be obvious. I'm trying to learn what I can as I encounter these problems. Thanks!
var categories = [ 'F', 'C', 'A1', 'A2', 'A3' ].map(function (category) {
return businesses.filter(function (business) {
return business.category === category;
});
});
해결책
The code given looks most likely to be using the jQuery JavaScript library that has some useful functions such as map()
for manipulating arrays.
The code assumes that you have a jQuery object / array, businesses
that contains the businesses that you need to order. If we read it from the outside in
- pass each item in the array in turn into the map function. The map function takes a function to say how each item should be mapped.
- The anonymous function
function (category)...
accepts one argument, the particular item passed to it in this iteration and will return the mapping result. - the result returned is a function of calling filter on
businesses
and passing it a function to say how businesses should be filtered. - The anonymous function
function (business)...
accepts an argument, the particular item passed to it asbusinesses
is iterated and returns those that match the category argument scoped in the outer function. - The end result is an array of items ordered by the category array
[ 'F', 'C', 'A1', 'A2', 'A3' ]
If we go back to the original problem, you need to order a list of categories based on the client's preference. Let's create a an object literal to map the ordering
var map = {
F : 5,
C : 3,
A1 : 1,
A2 : 4,
A3 : 2
}
We can use this map to order the array using the sort
method
var array = ['F', 'C', 'A1', 'A2', 'A3'];
array.sort(function(a,b) {
return map[a] - map[b];
});
This returns us ["A1", "A3", "C", "A2", "F"]