Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second.

I attempted the following method:

filtered = visibleColumns.filter(function(v) {
            return filtered.includes(v.colId);
        });

Although 'filtered' is supposed to be the resulting array and 'visibleColumns' represents the desired order, this approach did not yield the expected outcome.

Here are examples of the arrays:

filtered = [{
  colId:1,
  title: 'col1',
  size: 10
},
{
  colId:2,
  title: 'col2',
  size: 10
}];

visibleColumns = [{
  colId:2,
  visible: true
  },
{
  colId:1,
  visible: true
}];

Answer №1

If you want to customize the order of objects and handle unknown IDs by sorting them to the bottom, you can create a specific object for that purpose.

var filtered = [{ colId: 1, title: 'col1', size: 10 }, { colId: 2, title: 'col2', size: 10 }],
    visibleColumns = [{ colId: 2, visible: true }, { colId: 1, visible: true }],
    order = visibleColumns.reduce((o, { colId }, i) => (o[colId] = i + 1, o), {});

filtered.sort((a, b) => (order[a.colId] || Infinity) - (order[b.colId] || Infinity));

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To efficiently sort the array 'filtered' based on the order of 'visibleColumns', you can utilize a JavaScript Map. This Map object will map each 'colId' from 'visibleColumns' to its corresponding index in the array. By getting the index for each 'colId' while sorting 'filtered', you can achieve the desired result.

const filtered = [{ colId: 1, title: "col1", size: 10 }, { colId: 2, title: "col2", size: 10 }],
      visibleColumns = [{ colId: 2, visible: true }, { colId: 1, visible: true }];

const order = new Map(visibleColumns.map((o, i) => [o.colId, i]))

filtered.sort((a, b) => order.get(a.colId) - order.get(b.colId))

console.log(filtered)

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

Displaying an array as a column yields no visible results

Yesterday I posted a query regarding displaying an array with commas as columns. You can view the original question here. Today, my progress is as follows: <?php require_once("dbconnection.php"); ?> <?php $sql = "SELECT amount, ingredients FROM ...

Use jQuery to clear the content within a div element following the removal of an element

A dynamic generation of checkboxes is introduced to div1: $.each(json, function(idx, obj) { $("#tbl1").append('<input type="checkbox" id='+obj.firstId+' onclick=nextPopulate('+obj.firstId+'); >'); } Upon selection, ch ...

In C++ programming, we can create a system that allows users to input names and scores without any limitations on the number

I require assistance with an assignment. I am tasked with developing a program that collects names from the user, followed by 5 scores for each name. The number of names being inputted is indefinite. Once the user finishes entering the names and scores, th ...

Every time I attempt to use the reset() function in typescript, I encounter a type error that prevents its

I am encountering a type error message that reads: 9: Property 'reset' does not exist on type 'EventTarget'. 18 | }); 19 | 20 | e.target.reset() | ^^^^^ 21 | } Below is the relevant code snippet: const hand ...

Navigate to the top of the Vue scrollable list using v-auto-complete

I need to implement a feature that automatically scrolls to the top of a scrollable list every time the search input is changed. Currently, I have a list where multiple items can be selected, and I want it to reset to the top whenever a new search query is ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

Dependencies in Angular

After diving into Angular recently, I've been grasping the concepts well. However, one thing that still puzzles me is dependency injection. I'm unsure whether it's necessary to declare all components of my application (services, controllers ...

Analyzing individuals within an array

Currently, I am faced with a particular challenge. In my dataset, there is an array of individuals where some names are duplicated but not identical due to slight variations. My task involves iterating through all the names to assess their similarity, fol ...

Struggling to configure an onClick handler in Next.js

Unexpectedly, I was met with a surprise while trying to access react.dev, as it stated that create-react-app is no longer recommended for bootstrapping React applications. No worries, the world is always evolving. Let's explore Next.js for my first p ...

Navigate to a fresh webpage and find the scrollbar sitting at the bottom

When launching a new website using my forum system, I want the scrollbar to automatically be at the bottom so users don't have to scroll down. I'm not experienced in JavaScript and need help creating the code for this feature. ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Execute the function on the React template rendering process

How can I ensure that the getQuestions function is called when the template questionsCollected is rendered, without relying on an event trigger like onClick? The ajax call successfully retrieves the option items and logs them to the console. The template ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...

Webpack and TypeScript are throwing an error stating that `$styles` is not defined

I've encountered an issue with my typescript SharePoint spfx solution. After compiling using webpack, my $styles variable becomes undefined even though I am able to use the class names directly. It seems like there might be a configuration problem at ...

Unable to retrieve object property-Attempting to access properties of undefined object

Can you help me figure out why I am unable to access the districts property in regions object? const regions = [ { region: "Hlavní město Praha", districts: "Benešov, Beroun, Kladno, Kolín, Kutná Hora, Mělník, Mladá Boleslav, Nymbur ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

navigate to the subsequent array element by clicking in JavaScript

My apologies if my explanation is unclear or if the code seems complicated, I'm still in the learning process. I am attempting to showcase data that is stored in an array. The objective is to have this data displayed upon clicking a button and then sh ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...

Jasmine's await function often leads to variables remaining undefined

When testing a function, I encountered an issue where a variable is created and assigned a value, but the payload constant always remains undefined. campaigns-card.component.ts async ngOnInit() { const { uid } = await this.auth.currentUser const { ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...