Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple objects with the same lowest amount value. I need to extract all objects with the lowest amount value and place them in arrayLowest. The remaining objects should be stored in arrayHigher. How can I accomplish this using typescript?

this.arrayRevceived.sort(function (a,b)) {
    return a.amount - b.amount;
  }
    this.arraySorted = arrayReceived.splice(0,6);
 }
// it is working till here, the problem starts here
 for(let i =0; i < this.arraySorted.length; i ++) {
   if (this.arraySorted[0].amount === this.arraySorted[i].amount){
    this.arrayLowest.push(this.arraySorted[i]);
   } else {
    this.arrayHighest.push(this.arraySorted[i]);
  }
 }

In my attempt to achieve this, I am using a for loop to compare with index [0] because the array is already sorted, so the lowest value will be at index [0]. If the values match with subsequent objects, they are added to arrayLowest, otherwise to arrayHighest. However, this approach is not yielding the expected results. Any suggestions would be appreciated. Thank you.

Answer №1

Here is a solution for filtering out the lowest and highest values from an array.

let numbers = [
  { value: 50, id: 5 },
  { value: 30, id: 4 },
  { value: 10, id: 2 },
  { value: 70, id: 7 },
  { value: 60, id: 6 },
  { value: 10, id: 1 },
  { value: 20, id: 3 },
]

numbers.sort((a, b) => a.value - b.value);
numbers = numbers.splice(0, 6);

const lowestValues = [];
const highestValues = [];

numbers.map((val) => numbers[0].value === val.value ? lowestValues.push(val) : highestValues.push(val));

console.log(lowestValues);
console.log(highestValues);

Check out the working example on Stackblitz DEMO

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

Adding an additional element to an incoming array in Angular/Typescript/RxJS - a step-by-step guide

I recently encountered a challenge in my RxJS code involving the transformation of a list of JSON objects into items for a drop-down list. this.folders$ = this.folderStore.folders$.pipe( map((folders: GdFolder[]) => { const data = folders.map(fold ...

What is the best way to combine various ngrx selectors together?

I currently have 3 selectors in my index.ts file export const selectDetails = createSelector( // some code ); export const selectTransactionResponse = createSelector( // some code ); export const selectAdditionalDetails = createSelector( // some code ); ...

Angular application experiencing issues with loading React web component: encountering error when attempting to search for 'adoptedCallback' using 'in' operator with undefined value

I recently created a basic web component using React import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> He ...

Passing an observable from parameters to a pipe in RxJS: A guide

Can someone help me with writing a TypeScript function like the one below: function abc(arg1, arg2, arg3) { pipe(arg1, arg2, arg3...); // or someSubject.pipe(arg1, arg2, arg3..) } I keep getting errors when trying to build the code. How can I success ...

WebStorm provides alerts for objects, types, and directives within Angular, yet they function properly

Why is WebStorm displaying warnings for objects, types, and directives in Angular Template HTML even though they are functioning correctly? Despite the fact that all types and Angular directives in the HTML structure are working fine within Angular on Web ...

Synchronize Angular 5's provision of injection tokens

Is there a way to delay the provision of an InjectionToken until a previous provider's useFactory is finished? For instance, I would like to set MyInjectionToken only after the APP_INITIALIZER token has been allocated. providers: [ HttpClient, MySer ...

Angular component.html does not compile due to a check that includes inline array creation

There is an enum called Status: export enum Status { SOME_VAL = "SOME_VAL", SOME_VAL_2 = "SOME_VAL_2", SOME_VAL_3 = "SOME_VAL_3"; } Also, I have an interface named SomeInterface: export SomeInterface { status? ...

Is there a way to eliminate properties in typescript without relying on the option feature?

I am struggling with removing properties in TypeScript. type Person<GN> = { getName: GN extends never ? never : GN, } const foo = <GN>(person: Person<GN>) => person const first = foo({}) // This should work const second = fo ...

A guide on incorporating a single class object of type Observable<any> into HTML

I'm currently working with Angular4 and have a Windows Timer subscribed observable in my typescript file. this.dynamicTime = new Observable<string>((observer: Subscriber<string>) => { setInterval(() => observer.next(this ...

The IntrinsicAttributes type does not contain a property called 'theme'

As a junior TypeScript developer, I am exploring the creation of a dark mode feature using styled-components and a custom hook in TypeScript. useDarkMode.tsx import { useState } from 'react'; export const useDarkMode = () => { const [theme ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...

Is it possible to utilize an @Input() in Angular with multiple types?

Is it possible for a parent component to pass an object in @Input to the child component that may not always be the same? For instance, can I use: @Input() obj: string | number; In my scenario, I have two different objects as potential inputs: @Input() ob ...

Sluggish behavior detected in hybrid AngularJS and Angular application when accessed through Safari browser

Lately, I have embarked on the task of migrating an AngularJS application to Angular 4 using the upgrade module. Within my AngularJS directives, I am utilizing a third-party library (ngFlow) for file uploads via XMLHttpRequest.send(). Everything functions ...

Retrieve an Array Containing a Mix of Objects and Functions in Typescript

Let's address the issue at hand: I spent several months working with a custom React Hook using plain JavaScript, and here is the code: import { useState } from 'react'; const useForm = (initialValues) => { const [state, setState] = ...

Ways to limit file access and downloads on an IIS server

After deploying our Angular app (dist folder) on an IIS server, everything seems to be working well. However, there is a concerning issue where anyone can access and download the font files directly from the server without needing to log in. For example, o ...

Checkbox in the array has no assigned value

The checkbox in the array is causing me some trouble. I am currently developing a script for indoor soccer games to keep track of goalscorers and other game information, such as cards (green or red). Below is the code snippet for the away team table. The ...

In PHP, apply the "first" and "last" classes to strings that include one or more <p> tags

Currently, I am displaying two strings on a page # string 1 <p>paragraph1</p> # string 2 <p>paragraph1</p> <p>paragraph2</p> <p>paragraph3</p> My goal is to transform them as follows # string 1 <p class= ...

An error occurs when attempting to access a property that does not exist on type 'never'. Why is this considered an error rather than a warning?

I am experiencing an issue with the following code snippet: let count: number | undefined | null = 10; count = null; let result: string | undefined | null = count?.toFixed(2); console.log(`Result: ${result}`); The error message I received is as follows: ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...