Steps for locating and relocating an item to the top of a collection in an observable array

I'm new to Rxjs and have a good understanding of pipe, filter, sort, map, etc. However, I am struggling with a particular problem. I need to locate a specific item in the data returned by my observable and move it to the top of the list before displaying it. For instance, in this scenario, Darth Vader is currently in position 4 and I want to find him and move him to the first position in the array or collection. Check out this example for more details.

Answer №1

Is this the way you wanted it?

people$ = this.http.get('https://swapi.co/api/people/')
  .map((res:any) => {
    var _vader = res.results.splice(res.results.findIndex(x => x.name === 'Darth Vader'), 1);
    return [..._vader, ...res.results];
  });

Answer №2

import { Characters } from './star-wars-characters.model';

interface CharacterResults {
  numCharacters: Number,
  nextCharacter: String,
  prevCharacter: string,
  characterList: Characters[],
}

@Injectable()
export class StarWarsCharacterService {
    characters$ = this.http.get('https://swapi.co/api/characters/')
      .map((res: CharacterResults) => {
         return res.characterList.sort((a: Characters, b: Characters) => {
           return a.name === "Darth Vader" ? -1 : b.name === "Darth Vader" ? 1 : 0;
         });
        });

    constructor(private http: HttpClient) {} 
}

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

How can I obtain ViewContainerRef using ElementRef in Angular 6?

Sample <div my-directive></div> Directive Information constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {} utilizeService() { this.svc.doWork(vc, el); } As the service necessitates both a ViewContainerRef and an ElementRe ...

Dealing with circular references in class attributes within Angular

I'm facing a challenge in Angular while trying to set up mock data. I have the following two classes: export class Company { public id: number; public name: string; public applications: Application[]; constructor(id: number, name: string, ap ...

The unpredictable behavior of the `this` keyword while troubleshooting a TypeScript program in VS code

Upon further investigation, it seems that the issue I encountered was related to using Chrome for debugging my full application. This led me to question whether the problem stemmed from TypeScript or VS Code. Before submitting my findings, I decided to sw ...

New HTML5 feature: using the input type duration in forms

How can I utilize input type duration? I want users to be able to input a time duration in the format of 06:30:27:15 ( hh:mm:ss:ms ), allowing for values between (0-23:0-59:0-59:0-59). Any assistance would be greatly appreciated! IMPORTANT!: This impleme ...

Setting up an Angular CLI project

In our Angular 2 application, we utilize native CSS components that contain some JavaScript files. These components have wrappers to convert them into Angular 2 components. Now, I am looking to create a new Angular 4 project using Angular CLI and incorpora ...

Address the NPM alert regarding Bootstrap's 'unmet peer dependency' in Angular even if Bootstrap is not utilized

In my web project, I am using Angular 5.2.0 along with Bootstrap 4. To install Bootstrap 4, I used the command npm i bootstrap --save, which resulted in unmet peer dependencies warnings: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

Exploring the Attributes of Child Components in Angular 4 Unit Tests

Currently, I am in the process of upgrading my Angular 2 application to version 4.0.1 and encountering difficulties with some tests. Specifically, I am attempting to retrieve the attributes of a child component and verify that the provided value is accura ...

Obtaining a value from HTML and passing it to another component in Angular

I am facing an issue where I am trying to send a value from a web service to another component. The problem is that the value appears empty in the other component, even though I can see that the value is present when I use console.log() in the current comp ...

Simple solutions for creating Typescript declaration files effortlessly

Recently, I created a Javascript library using Typescript and I am seeking guidance on how to include a Declaration file in the distribution package. Can anyone recommend helpful tools available in Visual Studio 2015 for this purpose? ...

Error occurred in Next.js Lerna monorepo: Module parsing failed due to an unexpected token

Recently, I integrated a Next.js + TypeScript project into a Lerna monorepo. Upon running lerna build, it triggers tsc in all my packages and next build in the UI package. The tsc part performs as expected: $ yarn build yarn run v1.22.18 $ lerna run buil ...

An Angular and Electron application that dynamically queries either a web API or database based on the user's selected desktop or web mode

I am looking to develop an application using Angular and Electron that can be used on both desktop and browser platforms. I am considering utilizing the angular-electron starter kit, but I am open to exploring alternative options. One of my main concerns ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

Embedding Globalize.js into an Angular component

Hey there! I'm currently working on building an Angular 4 application that needs to support L10n. I've decided to incorporate globalize into my project. Below is a snippet of my App component: import { Component, OnInit } from '@angular/c ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

Loop through keys of an object using *ngFor

I have an object structured like this "Stage" : { // -> vaga.stage "ID01" : { // -> stage.code "abeb5220-2003-4b8b-a6d5-853a40ca7d60" : { //candidate "email" : "<a href="/cdn-cgi/l/email-protectio ...

Creating an array of input data for component, implementing data formatting in TypeScript for Angular or React applications

Here is an example of the input for the component. When this input is passed to the component, the output displays correctly. const data = [ ['Rank', 'Player', 'Player', 'Player'], ['1& ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...

The DefaultTheme in MaterialUI no longer recognizes the 'palette' property after transitioning from v4 to v5, causing it to stop functioning correctly

Currently in the process of transitioning my app from Material UI v4 to v5 and encountering a few challenges. One issue I'm facing is that the 'palette' property is not recognized by DefaultTheme from Material UI when used in makeStyles. Thi ...

Receiving an error when attempting to inject the Router in a component constructor without using the elvis operator

Upon launching my app, I desire the route /home to be automatically displayed. Unfortunately, the Angular 2 version I am utilizing does not support the "useAsDefault: true" property in route definitions. To address this issue, I considered implementing th ...