Arrange JSON response data in alphabetical order

Looking to sharpen my skills by working with public APIs in JavaScript. My goal is to sort the list of items alphabetically by the h4 value (food name) when the query is submitted. I attempted to use .sort() on the response item before using .map(), but ended up with a blank page. I also tried sorting the div elements with jQuery after the fact, but no luck. I'm new to JavaScript and coding this all in Notepad++, so there might be a better way to approach this that I'm not aware of.

HTML code:

<!DOCTYPE html>
<html>
<form action="search">
 <label>Search</label>
  <input type="text">
  <input type="submit">
  <input type="reset">
</form;

<div class="result">
 <h3>Result</h3>
</div>
</html>

CSS code:

.result{
 display:flex;
 flex-wrap:wrap;
}
.item{
  min-width:200px;
  margin:20px auto;
}

JavaScript code:

 var apiKey = "4b314d3e9171fbe99c6cdf16127ba93e";
 var apiId = "4c143c55";
 var queryItem;
 var url = 'https://trackapi.nutritionix.com/v2/search/instant?query=';

 var form = document.querySelector('form');
 var input = document.querySelector('input[type="text"]');
 var result = document.querySelector('.result');

 function search(e){
  e.preventDefault();
  queryItem = input.value;
  makeRequest(queryItem);
  input.value= "";
 }

 function reset(){
  var node = document.querySelector('.result');
  while (node.firstChild) {
  node.removeChild(node.firstChild);
 }
 }

 function createFood(name, qty, unit, photo){
 var item = document.createElement('div');
 var foodName = document.createElement('h4');
 var serving = document.createElement('p');
 var img = document.createElement('img');

 item.classList.add('item');
 foodName.innerHTML = name;
 serving.innerHTML = qty+' '+unit;
 img.src = photo;

 result.appendChild(item);
 item.appendChild(img);
 item.appendChild(foodName);
 item.appendChild(serving)

 }

 function makeRequest(queryItem) {
 reset();
 xhr = new XMLHttpRequest();

 xhr.onload = function() {
 var response = JSON.parse(this.responseText);

 response.common.map(function(food){
  createFood(food.food_name,
             food.serving_qty,
             food.serving_unit,
             food.photo.thumb
            )
  })
};

xhr.open(
 "GET",
 url+queryItem,
 true
);
xhr.setRequestHeader('x-app-id',apiId);
xhr.setRequestHeader('x-app-key',apiKey);
xhr.send();
}

form.addEventListener('submit', search)
form.addEventListener('reset', reset)

Answer №1

If you need to arrange an array of objects by a specific attribute, you can utilize a generic function designed for sorting based on the attribute's value.

function sortByAttributeAlphabeticallyASC(array, attribute) {
    return array.sort((a, b) =>
      a[attribute].toLocaleLowerCase().localeCompare(b[attribute].toLocaleLowerCase())
    );
}

Here, the array parameter represents the array of objects you wish to sort, while attribute denotes the attribute name to be used for comparison.

By referring to the Array documentation, you can observe that the sort method accepts a callback function for comparison.

Additionally, the String object features a method for comparing strings, detailed here, which can be incorporated within the Array::sort invocation for sorting needs.

To implement this function in your scenario, follow this pattern:

sortByAttributeAlphabeticallyASC(response.common, 'name').forEach(item => createItem(item.item_name,
    item.quantity,
    item.unit,
    item.image.thumbnail
))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The $OnChange function fails to activate when passing an object by reference

Hi there, I've encountered a problem in my code that I'd like some help with. In my example, I have two components: Parent Component and Child Component. Both components share a field called rules. The Parent Component passes the rules field to ...

What is the best approach to generate and organize 100 random numbers in a program, ensuring they are sorted in ascending order from 1 to 100?

I have successfully implemented the sorting and printout functionality of the program. However, I am now facing a challenge in generating 100 random numbers between 1 and 100, sorting them. I have created an array to store the generated numbers, and I ha ...

I have developed a website that can calculate the factorial of any given number. The next step is to design a function that will display the step-by-step mathematical process

Could use a hand with this one. The function below is empty and I'm a bit stuck on what to do next. Right now, the webpage displays the factorized number, but I want to show the mathematical equation before it, like so: User inputs: 3 Site outputs: " ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Exploring a different method for implementing animations during UI-router state transitions

My product owner presented me with a seemingly impossible challenge to create animations between states. I utilized ngAnimate and thought I had a brilliant solution - only to be told it wasn't what they wanted. "This isn't what I had in mind," h ...

Understanding the Importance of CSS Specificity in Resolving Selector Conflicts

I need help with a specific pseudo-class selector issue. Even with !important, the text in the li:first-child element is not appearing in blue. The selector specificity for p is: (0, 0, 1) The selector specificity for li:first-child is: (0, 1, 1) I want ...

What is the best way to conceal a set of columns and reveal them upon clicking a header column?

Currently working with Bootstrap 3 and successfully split the top into two columns. I am aiming to replicate the design shown in the sample image without relying on JavaScript or jQuery. Upon clicking "Quick Info", there should be a new set of columns reve ...

The mystery behind the enigmatic combination of ajax, JQuery,

Seeking Assistance! All fields are displaying undefined values function UpdateData(){ var id = $('#id').attr('value'); var name = $('#name').attr('value'); var department = $('#departament'). ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...

Styles in NEXT.js are not loading properly due to issues with the Module

I have been attempting to apply module.css to one of my components by following the instructions provided in this tutorial https://nextjs.org/learn/basics/assets-metadata-css/layout-component. /*/components/Livestream/App.js*/ import styles from './A ...

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

Utilizing Bootstrap in Laravel to align the heights of rows in adjacent columns

I am in the process of developing a calendar application that includes a header row and a header column. The layout displays six days in columns with a fixed number of time periods per day. <div class="row"> <div class="col-md c ...

Strange Phenomenon: Website Appears Enlarged When Accessed through Server

Similar Question: Why does my website appear smaller on a live server than when deployed locally? After reviewing the answer to the similar question linked above, I still found myself facing the same issue with no resolution. My problem is that the webpa ...

Differences between -webkit- and -moz-transition

My website uses CSS3 transitions and I have noticed that the -webkit- prefix works, but the -moz- prefix does not seem to be working. This is the CSS code I am using: article {z-index: 2; float: left; overflow: hidden; position: relative; -webkit-transit ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Utilizing multiple classes in HTML for a button element

  I've recently come across the concept that elements can have multiple classes. It's interesting, isn't it? .rfrsh-btn { background-image:url(../../upload/rfrsh_nb_grey.png); ... } .submit { font-size: 0.85em; paddi ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

Sharing JavaScript code between Maven modules can be achieved by following these steps

My Maven project has a unique structure that includes: "Base" module -- containing shared Java files -- should also include shared JavaScript files Module 1 -- using shared Java files as a Maven dependency -- should utilize shared JavaScript files throug ...