Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array?

This is my code in my.ts file:

initializeItems(){
    this.items = [
      { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian',  date:new Date().toLocaleDateString(), chat:'Life is beautiful...', component: TetherPage },
      { avatar: '../../assets/imgs/profile2.jpg', firstName:'Alexis', lastName:' Fournier ', date:'Yesterday', chat:'If you are going to use a passage...', component: TetherPage },
      { avatar: '../../assets/imgs/profile3.jpg', firstName:'Alma', lastName:'  Henry ', date:'10/1/2019', chat:'There are many variations of pass', component: TetherPage },
      { avatar: '../../assets/imgs/profile4.jpg', firstName:'Clara', lastName:' Damian ', date:'Today', chat:'nice to see you after log time ', component: TetherPage },
      { avatar: '../../assets/imgs/profile5.jpg', firstName:'James', lastName:' Charlie ', date:'Yesterday', chat:'Hi!..Have a nice day', component: TetherPage },
      { avatar: '../../assets/imgs/profile6.jpg', firstName:'Ellen', lastName:' Rhystem ', date:'2/1/2019', chat:'It is long establish fact...', component: TetherPage },
      { avatar: '../../assets/imgs/profile7.jpg', firstName:'Irene', lastName:' Reeceem ', date: new Date().toLocaleDateString(), chat:'I think we can all do with a bit more spark', component: TetherPage },
      { avatar: '../../assets/imgs/profile8.jpg', firstName:'Thomas', lastName:' Joe ', date:'Yesterday', chat:'you’re fired up ready to have the best day ever…', component: TetherPage },
      { avatar: '../../assets/imgs/profile9.jpg', firstName:'Charlie', lastName:' Kyle ', date:'3:45 am', chat:'Create the highest, grandest vision possible for your life, because you become what you believe', component: TetherPage },
      { avatar: '../../assets/imgs/profile10.jpg', firstName:'Jacob', lastName:' Henry ', date: new Date().toLocaleDateString(), chat:'Wherever life plants you, bloom with grace', component: TetherPage },
      { avatar: '../../assets/imgs/profile11.jpg', firstName:'Harry', lastName:' Callum ', date:'1/2/2019', chat:'One at a time. Just let your pile of good things grow', component: TetherPage },
      { avatar: '../../assets/imgs/profile12.jpg', firstName:'Oliver', lastName:' Jake ', date: new Date().toLocaleDateString(), chat:'Little by little, day by day, what is mean for you WILL find its way”', component: TetherPage },
      { avatar: '../../assets/imgs/profile13.jpg', firstName:'Jack', lastName:' Connor ', date:'Yesterday', chat:'Learn from yesterday, live for today, hope for tomorrow', component: TetherPage },
      { avatar: '../../assets/imgs/profile14.jpg', firstName:'Julia', lastName:' Margaret ', date: new Date().toLocaleDateString(), chat:'Take time to do what makes your soul happy', component: TetherPage },
      { avatar: '../../assets/imgs/profile15.jpg', firstName:'Jack', lastName:' Tracy ', date:'Today', chat:'Be so happy that when others look at you, they become happy too', component: TetherPage }
    ];
    this.modifiedData = JSON.parse(JSON.stringify(this.items));

}

Answer №1

To achieve the desired outcome, you can follow this example:

let data = [ {  title:'Inception', director:'Christopher Nolan', rating:9.3 }, {  title:'The Dark Knight', director:'Christopher Nolan', rating:9.0 }, {  title:'Interstellar', director:'Christopher Nolan', rating:8.6 } ];

data = sortByKey(data, 'rating');

function sortByKey(array, key) {
 return array.sort(function(a, b) {
    var x = a[key];
    var y = b[key];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

Answer №2

To organize the list, you can utilize Array.sort in combination with a personalized function for comparison that employs String.localCompare:

const sorted = items.sort((a, b) => a.firstName.localeCompare(b.firstName));

For further details, refer to the MDN documentation on Array.sort and String.localCompare.

const TetherPage = {};
// Rest of the code block remains unchanged
console.log(sorted);

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

What could be the reason for JSON refusing to accept an element from an array?

I am looking to retrieve the exchange rates for all currencies from an API using an array that lists all available currencies. Below is the JavaScript code I have written: var requestURL = 'https://api.fixer.io/latest'; var requestUrlstandard ...

javascript - Convert a string into a JSON object

Looking for assistance here as I am fairly new to this. My goal is to transform the fullName string returned from a webapp UI using Selenium WebDriverIO. Here's what I have: const fullName = "Mr Jason Biggs"; The desired outcome should be structured ...

Dropdown search menus are failing to appear in the correct location

I have 4 dependent search dropdown menus side by side. There are two issues I am facing: Whenever I type in any of the drop-down menus, the MySQL-connected lists appear but not directly beneath the actual 'input-type-search-box'. Additional ...

Changing the variable within a promise in Angular 1

There seems to be an issue with updating a variable within the callback function of a promise, as shown in the code snippet below: $scope.showSelected= function (node){ var promise = $http.get("http://127.0.0.1:5000/getResource?ldpr="+nod ...

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

Understanding TypeScript's ability to infer types in generics

Exploring the world of TypeScript through a robustly typed system for REST requests. Let's dive into the code: This type is used to establish the connection between routes and their respective object types: export interface RoutesMapping { api1: ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

I'm curious about this `express()` function in the `var express = require('express'); var app = express();` code. Is it a method or a constructor, and where does it originate from?

const express = require('express'); const app = express(); Behold, the birth of an express application. But wait, what is this 'express()' exactly? A method or a constructor perhaps? And where does it originate from? ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Incorporating a helper JavaScript file to seamlessly integrate Typeform into a project built with Vue

Struggling with incorporating a typeform into my website through the use of both vue and laravel. The problem arises when trying to embed the typeform using a script, as Vue throws an error when attempting to include the script directly within the compone ...

execute various scripts in content_scripts depending on the "matches" provided

I am new to JavaScript and currently working on customizing the script from the MDN tutorial, Your First WebExtension My goal is to draw either a red or blue box around a webpage based on whether it is http:// or https://. But I have encountered a proble ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

When running the PHP script, the output is shown in the console rather than in the

Here is a PHP script snippet that I am working with: <?php add_action('wp_ajax_nopriv_getuser', 'getuser'); add_action('wp_ajax_getuser', 'getuser'); function getuser($str) { global $wpdb; if(!wp_verif ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

Automatic suggestions for my personalized npm module (written in ES6/Babel) in Webstorm

When I utilize the material-ui package in Webstorm, I am able to experience helpful auto-completion using the ctrl+space shortcut: https://i.stack.imgur.com/Pivuw.png I speculated that this feature may be attributed to the inclusion of an index.es.js fil ...

Encounter a problem while installing node modules

I am facing an issue with my test directory which contains a package.json file: { "name": "test", "version": "0.0.1", "dependencies": { "hem": "~0.1.6", } } Upon trying to run node install, I encounter the following error: module.js:337 ...

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

Using Slick Slider and Bootstrap CSS to display text on top of images

Currently, I am utilizing the slick slider from and I want to overlay text on top of the image. I tried using bootstrap carousel-caption, which works well with any image. However, with slick slider, it seems like the text is not at the highest level as I ...

Designing a layout for a chat application that is structured from the bottom up

I'm currently in the process of designing a web application for a chat platform. I have access to an API that provides a list of messages: chatsite.com/api/thread/1/messages/ [ { "id": 2, "sender": { "id": 2, ...