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

Module for managing optional arguments in Node.js applications

I'm on the hunt for a Node.js module that can effectively manage and assign optional arguments. Let's consider a function signature like this: function foo(desc, opts, cb, extra, writable) { "desc" and "cb" are mandatory, while everything else ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

The middleware function encountered an undefined value in req.body

I've been attempting to validate my data retrieved from my express endpoint using yup. Despite watching numerous tutorials, I am encountering a particular error that has me stuck. Every time I try to validate the data in my middleware, it consistentl ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Can you provide the regular expression that will successfully match this specific string of text?

Can you solve this fruit riddle? apple is 2kg apple banana mango is 2kg apple apple apple is 6kg banana banana banana is 6kg If the fruits are limited to "apple", "banana", and "mango", how can we write a regex that extracts the names of ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this: <c:forEach var="var" items="${dataFile.list.rows}"> <li> <div> <a href="#" onClick="myFunct('${var.url}','escape(${var ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

Encountered issue when attempting to insert items into the list in EventInput array within FullCalendar and Angular

I am struggling to create a dynamic object that I need to frame and then pass to the FullCalendar event input. Here is my initial object: import { EventInput } from '@fullcalendar/core'; ... events: EventInput[]; this.events = [ { title: &ap ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

Error: AngularJS is experiencing an injector module error that has not been caught

I have set up an Angular boilerplate that includes various elements such as meta tags, CDN links, and script tags. However, I am encountering a persistent error in my console and cannot figure out the root cause of it. https://i.stack.imgur.com/qPGby.png ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...

To extract three records from storage and store them in the dbResult using a promise join technique

How can I efficiently retrieve and store 3 records in dbResult using promise join? Currently, I have code that retrieves a single record as shown below: req.oracleMobile.storage.getById(registry.getIncidentPhotoStorageName(), incident_id + '_01&apos ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...