Organize data alphabetically according to the names in the API

Can someone help me with sorting this image gallery by name?

Here is the HTML for the gallery:

<div>
  <div id="result"></div>
</div>

And here is the JavaScript code:

const container = document.getElementById('result');

function getData() {
  fetch('https://randomuser.me/api/?results=30')
    .then((response) => response.json())
    .then((results) => output(results));
}

function output(results) {
  const htmlData = results.results
    .map((result) =>
      `
    <div>
        <img src="${result.picture.large}">
        <div>${result.name.first}</div>
    </div>
    `
    ).join('');

  container.innerHTML += htmlData;
}

getData();

Answer №1

To implement sorting in your array, you can use the sort method

results.results
  .sort((a, b) => a.name.first.localeCompare(b.name.first))
  .map(...)

const container = document.getElementById('result');

function fetchData() {
  fetch('https://randomuser.me/api/?results=30')
    .then((response) => response.json())
    .then((results) => displayOutput(results));
}

function displayOutput(results) {
  const htmlData = results.results
    .sort((a, b) => a.name.first.localeCompare(b.name.first))
    .map((result) =>
      `
    <div>
        <img src="${result.picture.large}">
        <div>${result.name.first}</div>
    </div>
    `
    ).join('');

  container.innerHTML += htmlData;
}

fetchData();
<div>
  <div id="result"></div>
</div>

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

Preventing onmouseleave() from spreading to other siblings in vanilla JavaScript

If you visit gileslewey.com, you'll find the code I uploaded to easily identify the issue. On the website, I have implemented remote, animated .gif rollovers for each span tag in a series of headings. To vertically center the heading next to an image ...

Encountering Uncaught TypeError: data.find is not a function while working with a JSON array in React

I am currently diving into the world of React and working on a basic app. My goal is to fetch information from the Github API and display details about my repositories. However, I've hit a roadblock as I keep encountering an error while attempting to ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

Discover the ultimate guide on developing a personalized file management system using the powerful node.js platform!

I have undertaken a rather ambitious project for myself. There exists a comprehensive tutorial on the website that outlines the process of establishing an online environment (resembling a user panel) where registered users can effortlessly upload various ...

What is the best way to center the header on the page?

Struggling to align the header and images centrally on the page, I've been experimenting with the box model but haven't had much success. Being new to this area, any guidance or tips would be greatly appreciated. https://i.sstatic.net/ejR8L.png ...

Using GSAP to create a staggered animation with a negative delay

Seeking a Solution: I am curious if there is a method to incorporate a negative delay into the staggerFrom / staggerTo functions within greensock? Issue at Hand: The current animation I have in place is extending longer than desired. It would be benefic ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

When the div on a webpage is clicked, pass it within the same page using

Looking to implement a pop-up feature on click using Angular. The issue I'm facing is that when using a modal popup, it disappears automatically if clicked outside of it. Therefore, I'd like to know how to create a pop-up within the same page by ...

Creating custom styles for select dropdowns using only CSS

After spending nearly two hours scouring the internet, I couldn't find a single example of how to style a select dropdown with CSS. I was particularly interested in using z-index to display the select dropdown under an absolutely positioned div block. ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

Maintaining the scrolling behavior and preserving added class even after refreshing the page

I am facing an issue with an element on my page that adds a class when the user scrolls past a certain point and removes it when scrolling back up. The problem arises when I refresh the page after the class has been added, it doesn't persist until I s ...

What is the reason that the subscribe method is not invoked immediately after applying the groupBy operator

Why isn't the subscribe method of the second example being triggered? All logs within the pipe are functioning correctly in both examples. WORKING EXAMPLE: (although using hardcoded data and a different creator): of([ {tableName: 'table1&apo ...

Efficient method for quickly updating the color scheme of a grid of squares in JavaScript

Currently, I am developing a JavaScript game that features a 2D array of squares with background colors that update each frame. My current approach involves utilizing a borderless DOM table and setting the style.backgroundColor property of each cell every ...

Is there a way to make one column adjust its size automatically, while keeping another column in a fixed position?

The code I created is quite messy. I need the elements left-sbr and right-sbr to stay fixed in position, while allowing content to resize dynamically based on the browser or window size. Any suggestions on how to achieve this? .left-sbr{ width:240px; col ...

Having trouble with HTML5 prerender/prehresh not functioning properly (experiencing a loading/transition effect similar to a progressive curtain!

Currently, while working on my web project, I am experiencing a curtain-like loading effect for my photos and background. I would like them to instantly show up instead of gradually downloading. A progress bar is acceptable, but I do not want the curtain- ...

Steps for initiating a new dispatch once the previous one has concluded

Thank you for taking the time to read my query and offering your assistance. I apologize in advance for any language errors. I am currently working with redux and redux-thunk, and I am looking to trigger multiple dispatch actions in redux sequentially. Sp ...

Refreshing/Redrawing/Resizing a panel in jQuery Layout when toggling the visibility of a header or footer

Currently utilizing a standard jQuery layout with north, south, west, east, and center sections as outlined in the documentation. In both the west and center panels, there are header and footer panes included. While everything is functioning correctly, I ...

Quick way to determine the size of an array

Here is an array I am working with: var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}] I am trying to find out the length of the array where arr[x].a != 1. Can anyone suggest a better approach than using a for loop and push method? P.S I ...

"Efficiently incorporating a responsive sprite background image on your website -

Hey there! I am dealing with a situation where I have two columns of content in a container. The first column contains text, and the second column is a span with a background sprite image. The issue arises when the screen resolution gets smaller - I want ...

How to successfully submit an array using Vue.js

Having an issue with a form that allows users to enter multiple inputs of the same field as an array. However, encountering two errors when trying to submit the form. Error 1 : The value always returns as 'undefined', possibly due to incorrect a ...