skip to Main Content

I am using jQuery to make an AJAX call to pull data from an API –

const generateFilterOptions = () => {
$.ajax({
    method: 'GET',
    url: baseURL,
}).done(function (data, status, xhr) {
    let category = [];
    let categoryID = [];
    $.each(data, function (index, value) {
        category.push(value.field_resource_category);
        categoryID.push(value.field_resource_category_id);
    })
    category = [...new Set(category.toString().split(',').map(el => el.trim()))];
    categoryID = [...new Set(categoryID.toString().split(',').map(el => el.trim()))];
    category.forEach(
        (categoryName, id) =>
            $("#categoryFilter").append(`
                    <div class="d-flex align-items-start">
                        <input type="checkbox" name="${categoryName}" value="${categoryID[id]}" id="cat-${categoryID[id]}">
                        <label class="fs-6" for="cat-${categoryID[id]}">${categoryName}</label>
                    </div>
                    `)
    );
});

}

The values being returned are 1 to 2 digit numbers, and many of them are duplicates because it’s pulling the ID of a category, and many of the results share the same category.

The markup must include the name that being pulled, as well as the category ID, and it is for a filter so the results cannot be duplicated.

category.push(value.field_resource_category);
categoryID.push(value.field_resource_category_id);

I start by pushing the values into their own arrays

category = [...new Set(category.toString().split(',').map(el => el.trim()))];
categoryID = [...new Set(categoryID.toString().split(',').map(el => el.trim()))];

Then I use Set() to remove any duplicates. toString() to change from array to a string, split() to remove the comma, then .map with .trim() to remove whitespace

category.forEach(
    (categoryName, id) =>
        $("#categoryFilter").append(`
            <div class="d-flex align-items-start">
                <input type="checkbox" name="${categoryName}" value="${categoryID[id]}" id="cat-${categoryID[id]}">
                <label class="fs-6" for="cat-${categoryID[id]}">${categoryName}</label>
            </div>
        `)
);

Then I have a for each loop that returns the name and ID so I can put it into my HTML markup.

I need to manipulate the results so that they are in alphabetical order.

I tried to add in .sort(), but the problem is the ID that’s being returned is a string not a number, so 11 comes before 2 in alphabetical order

2

Answers


  1. You can sort number strings by converting them to numbers and subtracting one from the other to determine their order.

    const x = [
      "21",
      "1",
      "2000",
      "11",
      "132",
    ].sort((a, b) => Number(a) - Number(b));
    
    console.log(x);
    Login or Signup to reply.
  2. even shorter than @ray’s solution:

    const x = [
      "21",
      "1",
      "2000",
      "11",
      "132",
    ].sort((a, b) =>a-b);
    
    console.log(x);

    The strings are automatically translated to numbers depending on the operation that’s being done. You don’t need to worry. That’s called type coersion and though controversial it’s a ‘feature’ of Javascript.
    Just be aware of edge cases: https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch04.html
    (check section "Edge cases")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search