Arranging an array of objects in Angular 7 according to the order of another array of objects

Yes, I know this question has been asked a million times before. However, I haven't found any helpful answers in those previous questions.

Here's my dilemma: I have two arrays containing two different objects, each with a unique string property used to identify them. This property would be the key to sort them, but the names of the properties in the objects are not the same (accessValue, modifiedOption). Despite this, their values are identical.

 Object1: { ... accessValue, ... };

 Object2: { ..., modifiedOption, ... }; 

 array1: Object1[];

 array2: Object2[];

My goal is to sort array1 based on the order of objects in array2. Essentially, I want all items in array1 to be in the same order as array2.

These arrays are part of a connected dropdown selection system that can be dynamically updated. However, adding new elements is causing issues (the last added item is not placed at the end). This may be due to the filter function in the code below:

When adding new dropdowns:

 addFieldRow() {
    this.fieldRows.push(0); // Indicates an unknown selection, populating the array to display a second dropdown
    ...
}

public onSelect() {
    this.fieldRows = this.editOptions.filter(
        option => this.selectedOptions.some(el => el.modifiedOption === option.accessValue)
    );
    this.disableSelected(); 
    this.optionSelected = true; 
}

Therefore, I need to either fix my addRow logic or implement a sorting utility to ensure that the objects in fieldRows are ordered the same as the selectedOptions array, as it directly corresponds to the selection model.

Unfortunately, I can't provide a StackBlitz example as it's difficult to replicate my current situation.

Answer №1

Wow, I can't believe how foolish I was! I realized that by knowing the current index (since I am looping through fieldRows).

All I needed to do was make this change:

  public onSelect(index) {

    this.fieldRows[index] = this.editOptions.find(option => this.selectedOptions[index].modifiedOption === option.accessValue);
    this.disableSelected();
    this.optionSelected = true;
  }

And just like that, it started working properly!

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

Is there a way to condense a function into a single line in Python?

def height (t): if not t: return 0 # (1) elif not t.nodes: return 1 # (2) else: return 1 + max(height(n) for n in t.nodes) # (3) Hello everyone! Can someone assist me in ...

I am seeking advice on how to separate words and special characters within a string

My text looks like this: String responseBody = ["{\"event\":{\"commonEventHeader\":{\"sourceId\":\"\",\"startEpochMicrosec\":\"1590633627120000\",\"eventId\":\"135.16.61.40-Fault_ ...

Utilize ng-content to access the component provider within a child component

I have been utilizing the ngx-mapbox-gl library, found at this link. This library includes a component called "mgl-map", which allows users to add child layer components that will render on the map. My objective is to create a parent component that contai ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

What is the process for setting up a single timer in a non-singleton application service?

My goal is to send a GET request every X seconds. To achieve this, I have implemented a timer in the constructor of a service which is then injected into a component for use. I want the service (as a singleton) to handle scheduling the GET requests at regu ...

Error: Your call to the "useFormState" function does not match any available

I am fairly new to web application development and I'm facing an issue with the useFormState function. I am currently working on building an edit form for database entries, but the code that previously worked is now throwing an error stating that ther ...

How to effectively organize an array of objects retrieved from a Mongoose query?

I am currently working with the following schema: const userSchema = new Schema({ local: { email: {type: String, unique: true, sparse: true, lowercase: true, trim: true, required: true}, password: {type: String, required: true}, }, username: ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement: In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their val ...

What could be causing the index.tsx file to not locate the Clock Module?

Here is the code snippet I have in my index.tsx file. import Clock from "./utility/clock"; And this is my tsconfig setup. { "compilerOptions": { "sourceMap": true, "noImplicitAny": true, "module": "es6", "target": "es5", ...

Guide on utilizing Angular CDK Drag and Drop library for uploading files

I've been working on a unique angular file-upload component and wanted to integrate Angular CDK drag&drop for an enhanced user experience. Unfortunately, when attempting to use it for file uploads (dragging files into the dropzone), I encountered ...

How do I submit an array of objects in Laravel?

I am currently working with a dynamic table that allows users to add and delete rows. Each row contains input fields where users can enter data for an object. At the moment, I am manually assigning index numbers to the name attribute like this: <input ...

Filepicker.io (Filestack) has the capability to upload files in duplicate

Incorporating Filestack (also known as filepicker.io) into my Angular 4 application has resulted in an issue where, upon file selection but before uploading, the file is automatically being uploaded. Consequently, when I click Upload, two files end up bein ...

I recently made the switch to Angular 9.0 for my project, but when I ran the build using yarn, I encountered some warnings. Despite the

I encountered this issue on both Ubuntu 16.04 and 18. I have tried various solutions such as reinstalling yarn, node, and clearing the cache, but the warnings persist. For every build using a script, the node_modules folder is deleted and then reinstalled ...

Utilizing Typescript and RequireJS for Incorporating jqueryui

Recently, I've been encountering issues with getting jQueryUI to function properly. Strangely enough, prior to attempting to integrate jQueryUI, using jQuery alone worked perfectly fine. The current problem I'm facing is receiving a "TypeError: ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Cancel the previous Angular/RxJS request to unsubscribe

I'm on the quest for a more streamlined approach using RxJS to tackle this task. The existing code gets the job done, but it seems like there should be a more efficient solution. ngOnInit() { this.activatedRoute.params.subscribe(({ bookId }) => ...

Looking to retrieve the request body in a route handler in Next.js version 13.2?

I encountered an issue while attempting to send a post request to my API. The problem arises when I try to access the request body within the route handler, resulting in the following error: Code: export async function POST(request: Request) { const ...