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

Manipulating, modifying, and verifying distinct information rather than inputting to / retrieving from the model through the use of Reactive Forms

My configuration I am retrieving a value from the database as a number. This value must always be a number, except when displaying it in an input element and validating user input. In those cases, the number needs to be a HEX value. Here is the desired p ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

Determining the type inference in Typescript based on column data objects

Within my object that describes my table, I have a property called dataFields, which is an array of data with 3 keys - name (a required string), label (a required string), and field (an optional string). Now, I would like to add another property called tes ...

Randomly rearranging a list of names to generate a new list organized according to two specific criteria

Here is a list of names: $names = array( "Alberto", "Bianca", "Claudio", "Douglas", "Erica" ); I want to randomly sort this list to create a mapping like so: $mapping = array( ...

Using React Testing Library with TypeScript revealed issues with ES6 modules causing test failures

I am currently working on a small project that involves React, Typescript, and Mui v5. The application is relatively small and uses the default Create React App setup. Although I am new to unit and integration testing, I am eager to make use of the tools ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Removing the arrow icon preceding an image in a new line when dealing with dynamic data

My Angular project renders dynamic content that includes the following HTML structure: <div class="complted" *ngFor="let step of letStep1to7; let i = index; let first = first"> <table> <td class="steps" ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Arrange the elements in a column of a multi-dimensional array in descending order while maintaining their respective keys

I have an array that needs to be sorted based on the 'answer' value in each 'scores' array, from high to low. $array = [ 503 => [ 'scores' => [ 4573 => ['answer' => 100], ...

Choose a specific interface in Typescript

I am interested in developing a React alert component that can be customized with different message colors based on a specific prop. For example, I envision the component as <alert id="component" info/> or <alert id="component" ...

`Unresponsiveness in updating bound property after change in Angular2 child property`

Having trouble with my custom directive and ngOnChanges() not firing when changing a child property of the input. my.component.ts import {Component} from 'angular2/core'; import {MyDirective} from './my.directive'; @Component({ d ...

Is the relevance of Angular 1.x still prevalent in today's development landscape

Considering I have several projects in angular 1.x, I'm contemplating whether it's truly essential and efficient to upgrade them to angular 4 or a later version. The smaller dashboards do not necessarily require an update since they are only use ...

JSON Response Handler

Here is the coding structure I am currently utilizing: func extractData(){ URLSession.shared.dataTask(with:apiURL!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { ...

Previewing files from external URLs with Ionic 5 Capacitor and Angular

I recently implemented the previewanyfile cordova plugin in my Ionic 5 application to open files from external URLs. While it works smoothly on Android devices, I have encountered an issue on iOS where some PDF files fail to preview and instead display a g ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

Error TS2345: The argument provided, which is of type 'Promise<ReadonlyArray<Object>>', cannot be assigned to a parameter that must be of type 'T | PromiseLike<T> | undefined'

My goal is to return the ReadonlyArray<> in my promise so that I can send it back to the original method that called 'dispatchToThisProcess'. This abstraction allows for potential future updates to multiple processes. Below is the code snip ...

The import of type cannot be done within paths in tsconfig

Currently, I am tackling a server side project utilizing TypeScript. In this context, I have established various types in ooo.d.ts and configured the paths within tsconfig.json. However, upon attempting to import the specified type, an error is being displ ...

What is the method for generating a fresh array that includes information from a different array using React Native?

Can you guide me on how to generate a new array from an existing one? The array I have is called data1. this.state = { data1: [ {'x':'%20', 'y':11, 'z':'sunday'}, {'x':' ...

Playing around with TypeScript + lambda expressions + lambda tiers (AWS)

Having trouble importing modules for jest tests in a setup involving lambdas, lambda layers, and tests. Here is the file structure: backend/ ├─ jest.config.js ├─ package.json ├─ babel.config.js ├─ layers/ │ ├─ tsconfig.json │ ├ ...